C# 简单5位数字验证码小练习(GDI+)
随机生成5位数字,随机字体,随机颜色,以图片方式显示出,并画出若干直线和点。达到简单验证码效果。
界面设计:
代码:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace GDI_验证码
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string str = "";//字符串变量
private void pictureBox1_Click(object sender, EventArgs e)//图片框单击事件
{
YZM();//调用方法
}
private void button1_Click(object sender, EventArgs e)//按钮 单击事件
{
if (str == txtYZM.Text)//判断随机的5位数字和文本框输入字符串 是否相同
{
MessageBox.Show("验证码正确!", "正确", MessageBoxButtons.OK, MessageBoxIcon.Information);//提示
txtYZM.Clear();//清空文本框
YZM();//调用方法
}
else
{
MessageBox.Show("验证码不正确!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);//提示
txtYZM.Clear();//清空文本框
YZM();//调用方法
}
}
void YZM()//方法
{
Random r = new Random();//随机数生成器
str = "";//字符串为空
txtYZM.Clear();//清空文本框
for (int i = 0; i < 5; i++)//循环 5位随机数
{
str += (r.Next(0, 10).ToString());//得到5位随机数,并转换为字符串,赋值给str
}
Bitmap bmp = new Bitmap(80, 21);//位图 指定大小
Graphics g = Graphics.FromImage(bmp);//封装一个 GDI+ 绘图图面。
for (int i = 0; i < 5; i++)//循环
{
string[] fonts = { "微软雅黑", "宋体", "黑体", "楷体", "仿宋", "新宋体" };//用于随机字体
Color[] colors = { Color.Blue, Color.Green, Color.Cyan, Color.Black, Color.Red, Color.Yellow };//用于随机颜色
Point p = new Point(i * 15, 0);//用于指定随机数字位置
g.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 6)], 12, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 6)]), p);
//5位随机数,每个随机数,随机字体,颜色和位置。
}
for (int i = 0; i < 8; i++)//循环
{
Point p1 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));//随机点
Point p2 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));//随机点
g.DrawLine(new Pen(Brushes.Green), p1, p2);//绘制直线
}
for (int i = 0; i < 15; i++)//循环
{
Point p = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));//随机点
bmp.SetPixel(p.X, p.Y, Color.Black);//绘制 点。
}
pictureBox1.Image = bmp;//将生成位图 设置到pictureBox1框上。
}
private void Form1_Load(object sender, EventArgs e)//窗体默认加载
{
YZM();//调用方法
}
}
}输出结果:
