C#生成随机验证码
一个lable,一个pictureBox,一个textBox和一个button;
具体代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace 创建验证码
{
public partial class Form1 : Form
{
string yzm;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CreateImage(yzm=CreateCode());
this.Text = "创建验证码 by江南小驴";
}
/// <summary>
/// 产生四位随即验证码
/// </summary>
/// <returns></returns>
private string CreateCode()
{
char[] ch=new char[4];
string str=null;
int i;
int number;
Random random = new Random();
for (i = 0; i < 4; i++)
{
number = random.Next(62);//0~9,a~z,A~Z共62位
if (number < 10)
ch[i] = (char)('0' + (char)number);
else if (number < 36)
ch[i] = (char)('a' + (char)(number-10));
else ch[i] = (char)('A' + (char)(number-36));
str += ch[i].ToString();
}
return str;
}
/// <summary>
/// 生成随即验证码图形
/// </summary>
/// <param name="code"></param>
private void CreateImage(string code)
{
//建立位图文件,设置长宽
System.Drawing.Bitmap image=new
System.Drawing.Bitmap((int)Math.Ceiling(code.Length*20.0),30);
Graphics g = Graphics.FromImage(image);
try
{
int i;
//生成随即生成器
Random random = new Random();
//情况图片背景色
g.Clear(Color.Gray);
//设置图片上各字符的颜色
int red, green, blue;
Color[] color = new Color[4];
for(i=0;i<4;i++)
{
red = random.Next(256);
green = random.Next(256);
blue = random.Next(256);
color[i]=Color.FromArgb(red,green,blue);
}
//生成背景噪音线
for (i = 0; i < 5; i++)
{
int x1 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int x2 = random.Next(image.Width);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Purple), x1, y1, x2, y2);
}
//将产生的随即数以字体的形式写入画面
Font font = new System.Drawing.Font("Arial",19,System.Drawing.FontStyle.Bold);
for (i = 0; i <4; i++)
{
g.DrawString(code.Substring(i, 1), font, new SolidBrush(color[i]),i*image.Width/4+2, 4,null);
}
//生成前背景噪点
Point[] zdian = new Point[150];
for (i = 0; i < 150; i++)
{
zdian[i].X = random.Next(image.Width);
zdian[i].Y = random.Next(image.Height);
image.SetPixel(zdian[i].X, zdian[i].Y, Color.FromArgb(random.Next(256), random.Next(256), random.Next(256)));
}
//画图片的边框
g.DrawRectangle(new Pen(Color.Green), 0, 0, image.Width-1, image.Height-1 );
this.pictureBox1.Width = image.Width;
this.pictureBox1.Height = image.Height;
this.pictureBox1.BackgroundImage = image;
}
catch (SyntaxErrorException ex)
{
MessageBox.Show(ex.ToString(),"错误提示",MessageBoxButtons.OKCancel);
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
CreateImage(yzm=CreateCode());
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.ToLower() == yzm.ToLower())
{
MessageBox.Show("小样,眼力挺尖!");
}
else
{
MessageBox.Show("恭喜,你看错了");
}
}
}
}
效果输出