c# +winform验证码生成并验证(通过创建公共类来实现)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
#region//调用验证码函数
CodeImage(CheckCode());
#endregion
}

private string CheckCode()
{
#region//生成随机数
int number;
char code;
string checkcode = string.Empty;//声明变量存储随机生成的4位英文或数字
Random random = new Random();//生成随机数
for (int i = 0; i < 4; i++)
{
number = random.Next();//返回非负随机数
if (number % 2 == 0)//判断数字是否为偶数
code = (char)('0' + (char)(number % 10));
else //如果不是偶数
code = (char)('A' + (char)(number % 26));
checkcode += "" + code.ToString(); //累加字符串

}
test.strUpper = checkcode.ToUpper();//转化成大写的验证码
test.strLower = checkcode.ToLower();//转化成小写的验证码
return checkcode;//返回生成的字符串
#endregion
}
private void CodeImage(string checkcode)
{
#region//生成背景图
if (checkcode == null || checkcode.Trim() == string.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkcode.Length * 12.5)), 22);//可以控制显示验证码的区域
Graphics g = Graphics.FromImage(image);//创建Graphics对象
try
{
Random random = new Random();//生成随机生成器
g.Clear(Color.White);//清空图片背景色
for (int i = 0; i <5; i++)//画图片的背景噪音线
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);//把两点坐标用线连接起来
}
Font font = new Font("Arial", 12, (System.Drawing.FontStyle.Bold));//指定字体大小和样式
g.DrawString(checkcode, font, new SolidBrush(Color.Red),2, 2);//绘制文本字符串
for (int i = 0; i < 150; i++)//画图片的前景噪点
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));//设置像素
}
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);//绘制矩形
this.pictureBox1.Width = image.Width;//设置pictureBox1的宽度
this.pictureBox1.Height = image.Height;//设置pictureBox1的高度
this.pictureBox1.BackgroundImage = image;//设置pictureBox1的背景图像
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
}
private void button1_Click(object sender, EventArgs e)
{
#region//刷新验证码
CodeImage(CheckCode());
#endregion
}

private void button2_Click(object sender, EventArgs e)
{
//如果文本框输入的验证码和随机生成的验证相等
if (textBox1.Text.Trim() == test.strUpper || textBox1.Text.Trim() == test.strLower)
MessageBox.Show("验证码正确");
else
MessageBox.Show("验证码错误");
}
}
}

//注释:其中strUpper, strLower为test类中的变量。以下截图为test创建过程

//功能测试截图

原文地址:https://www.cnblogs.com/thbbsky/p/2732548.html