介绍下Winform实现验证码的步骤:
首先拖入控件:PictureBox显示验证码;TextBox输入验证码;Check按钮;Label标签-点击更换验证码;
1.随机产生一个4位的字符串,由数字,大小写字母组成:
string RandomCode() { string retCode = ""; for (int i = 0; i < 4; i++) { while (true) { int id = rd.Next(48, 122); if (id >= 48 && id <= 57 || id >= 65 && id <= 90 || id >= 97 && id <= 122) { retCode += Convert.ToChar(id).ToString(); break; } } } return retCode; }
2.创建画板:
Bitmap bMap = new Bitmap(this.pictureBox1.Width,this.pictureBox1.Height); Graphics g = Graphics.FromImage(bMap); g.Clear(Color.LightGray);
3.在画板上画几条颜色随机的线条:
for (int i = 0; i < 8; i++) { int x1 = rd.Next(bMap.Width); int y1 = rd.Next(bMap.Height); int x2 = rd.Next(bMap.Width); int y2 = rd.Next(bMap.Height); g.DrawLine(new Pen(Color.FromArgb(rd.Next())), x1, y1, x2, y2); }
4.画一些背景噪点,颜色随机:
for (int i = 0; i < 600; i++) { int x = rd.Next(this.pictureBox1.Width); int y = rd.Next(this.pictureBox1.Height); bMap.SetPixel(x, y, Color.FromArgb(rd.Next())); }
5.画验证码:
Font ft = new Font("宋体", 24, FontStyle.Bold | FontStyle.Italic); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush( new Rectangle(0, 0, bMap.Width, bMap.Height), Color.OrangeRed, Color.DarkOrchid, 1.2f, true); for (int i = 0; i < codeStr.Length; i++) { g.DrawString(codeStr[i].ToString(), ft, brush, 5 + 23 * i, -1); }
6.将画好的图像赋给PictureBox:
this.pictureBox1.Image = bMap; g.Dispose(); ft.Dispose();
7.按钮点击事件:
private void Form1_Load(object sender, EventArgs e) { rd = new Random(); CreateCodeImage(checkCode = RandomCode()); } private void label1_Click(object sender, EventArgs e) { CreateCodeImage(checkCode = RandomCode()); } private void button1_Click(object sender, EventArgs e) { if (textBox1.Text != checkCode) { MessageBox.Show("验证失败,请重新输入", "提示"); CreateCodeImage(checkCode = RandomCode()); } else MessageBox.Show("验证通过", "提示"); }
x效果展示:
标签:功能,int,验证码,Next,rd,bMap,new,Winform From: https://www.cnblogs.com/cfsl/p/17675090.html