您的位置:首页 > 编程语言 > C#

C# 数字验证码设计

2018-02-06 22:08 274 查看
设计步骤

(1)创建Windows应用程序项目,在窗体Form1上添加一个标签和一个按钮;一个文本框控件和一个图片框控件pictureBox。

(2)编写代码

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string str_ValidateCode;
//生成任意长度的字符串
public string GetRandomNumberString(int int_NumberLength)
{
string str_Number = string.Empty; //表示空字符串。此字段为只读。
Random theRandomNumber = new Random();
for(int int_index=0;int_index<int_NumberLength;int_index++)
{
str_Number += theRandomNumber.Next(10).ToString();
}
return str_Number;
}
//生成验证码的随机颜色
public Color GetRandomColor()
{
Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
//对于C#的随机数,没什么好说的
System.Threading.Thread.Sleep(RandomNum_First.Next(50));
Random RandomNum_Second = new Random((int)DateTime.Now.Ticks);
//为了在白色背景上显示,尽量生成深色
int int_Red = RandomNum_First.Next(256);
int int_Green = RandomNum_Second.Next(256);
int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
int_Blue = (int_Blue > 255) ? 255 : int_Blue;
return Color.FromArgb(int_Red, int_Green, int_Blue);
}
//根据字符串生成图像
public void CreateImage(string str_ValidateCode)
{
int int_ImageWidth = str_ValidateCode.Length *13;
Random newRandom = new Random();
//图高20px
Bitmap theBitmap = new Bitmap(int_ImageWidth, 20);
Graphics theGraphics = Graphics.FromImage(theBitmap);
//白色背景
theGraphics.Clear(Color.White);
//灰色边框
theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, 19);
//10pt字体
Font theFont = new Font("Arial", 10);
for(int int_index=0;int_index<str_ValidateCode.Length;int_index++)
{
string str_char = str_ValidateCode.Substring(int_index,1);
Brush newBrush = new SolidBrush(GetRandomColor());
Point thePos = new Point(int_index * 13 + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
theGraphics.DrawString(str_char, theFont, newBrush, thePos);
}
//将生成的图片显示在图片框中
pictureBox1.Image = theBitmap;
}

private void Form1_Load(object sender, EventArgs e)
{
//4位数字验证码
str_ValidateCode = GetRandomNumberString(4);
CreateImage(str_ValidateCode);
}

private void button1_Click(object sender, EventArgs e)
{
if(str_ValidateCode==textBox1.Text)
{
MessageBox.Show("验证通过");
}
else
{
MessageBox.Show("验证失败,请再输入一次");
}
}
} 结果显示;                                
                                         
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: