运行结果:
代码:
1) VS2015 新建一个WindowsFormsApplication工程,
2) 在Form1.cs中,添加如下控件:
表 窗体及控件属性设置
窗体和控件 | 属性 | 属性值 |
Form1 | Text | 验证码 |
pictureBox1 | Name | pictureBoxCode |
textBox1 | Name | txtCode |
button1 | Name | btnCheck |
Text | 验证 |
3) 鼠标右击Form1.cs 找到对应的代码工程,代码部分参考如下代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//功能 : 验证码的生成与匹配
namespace WinFormsVerificationCode
{
public partial class Form1 : Form
{
//在主窗体中定义全局变量
string randomCode = string.Empty;
//方法:生成随机字符串
private string CreateRandomCode(int codeCount)
{
string randomCode = "";
string allchar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
string[] allCharArray = allchar.Split(',');//分割 生成子串
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
//生成随机数 且 该随机数<=allCharArray.Length
randomCode += allCharArray[rand.Next(allCharArray.Length)].ToString();
}
return randomCode;
}
//方法:生成验证码图像
private Bitmap CreateImage(string code, int fontSize, string font, Color foreColor, Color bgColor)
{
int imageWidth = (code.Length * fontSize) + 40;//图片宽度
int imageHeight = fontSize * 2 + 10;//图片高度
Bitmap image = new Bitmap(imageWidth, imageHeight);//生成图片框
Graphics g = Graphics.FromImage(image);
g.Clear(bgColor);
Font f = new Font(font, fontSize, FontStyle.Bold);
//使用指定的画笔和字体对象在指定位置绘制指定的文本字符串。
g.DrawString(code, f, new SolidBrush(ForeColor), 1, 1);//设置验证码
Random rnd = new Random();
//给背景添加随机生成的燥点
for (int i = 0; i < 100; i++)
{
int x = rnd.Next(imageWidth);
int y = rnd.Next(imageHeight);
g.FillRectangle(new SolidBrush(Color.FromArgb(rnd.Next())), x, y, 2, 2);
}
//给背景添加随机生成的干扰线
for (int i = 0; i < 50; i++)
{
int x1 = rnd.Next(imageWidth);
int x2 = rnd.Next(imageWidth);
int y1 = rnd.Next(imageHeight);
int y2 = rnd.Next(imageHeight);
g.DrawLine(new Pen(Color.FromArgb(rnd.Next()), 2), x1, y1, x2, y2);
}
return image;
}
//方法:刷新验证码
private void freshCode()
{
randomCode = CreateRandomCode(5);
pictureBoxCode.Image = CreateImage(randomCode, 35, "宋体", Color.Blue, Color.White);
}
public Form1()
{
InitializeComponent();
}
//按钮点击事件处理程序
private void btnCheck_Click(object sender, EventArgs e)
{
if (randomCode.ToUpper() != txtCode.Text.ToUpper())
{
MessageBox.Show("验证码输入错误,请重新输出!");
txtCode.Text = "";
freshCode();
}
else
{
MessageBox.Show("恭喜,验证码输入正确!");
}
}
//窗体加载事件处理程序
private void Form1_Load(object sender, EventArgs e)
{
freshCode();
}
}
}