C#生成验证码的两种方法

博客介绍了在C#中实现网页登录验证码的两种方式。第一种通过简单的随机数生成验证码并进行验证;第二种不仅生成包含数字和字母的验证码,还绘制出可视化的验证码。同时推荐使用第一种方式,因其简单高效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时候在网页中登录时需要输入验证码,C#中也可以做到,以下是两种不同的方式:

第一种方式:

  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. if (textBox3.Text != label4.Text) //验证码输入有误
  4. {
  5. MessageBox.Show("验证码输入错误!!!");
  6. Random rnd = new Random();
  7. //生成验证码
  8. this.label4.Text = rnd.Next(1000, 9999).ToString(); //验证码取值范围
  9. }
  10. else
  11. {
  12. if (radioButton1.Checked) //管理员登录
  13. {
  14. if (textBox1.Text == "admin" && textBox2.Text == "admin")
  15. {
  16. Admin frm = new Admin();
  17. frm.Show();
  18. this.Hide();
  19. }
  20. else
  21. {
  22. MessageBox.Show("密码错误或者该用户不存在!!!");
  23. textBox1.Text = "";
  24. textBox2.Text = "";
  25. textBox3.Text = "";
  26. }
  27. }
  28. }
  29. }

第二种方式:(推荐使用第一种,简单高效)

  1. private void CreateVerificationCode(int CodeCount)
  2. {
  3. #region 产生验证码
  4. string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
  5. string[] allCharArray = allChar.Split(',');
  6. string RandomCode = "";
  7. int temp = -1;
  8.  
  9. Random rand = new Random();
  10. for (int i = 0; i < CodeCount; i++)
  11. {
  12. if (temp != -1)
  13. {
  14. rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
  15. }
  16.  
  17. int t = rand.Next(33);
  18.  
  19. while (temp == t)
  20. {
  21. t = rand.Next(33);
  22. }
  23.  
  24. temp = t;
  25. RandomCode += allCharArray[t];
  26. }
  27. checkCode = RandomCode;
  28.  
  29. #endregion
  30.  
  31. #region 绘制验证码
  32. int iwidth = (int)(checkCode.Length * 14);
  33. System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 21);
  34. Graphics g = Graphics.FromImage(image);
  35. Font f = new System.Drawing.Font("Arial ", 10);//, System.Drawing.FontStyle.Bold);
  36. Brush b = new System.Drawing.SolidBrush(Color.Black);
  37. Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));
  38.  
  39. g.Clear(System.Drawing.ColorTranslator.FromHtml("#99C1CB"));//背景色
  40.  
  41. char[] ch = checkCode.ToCharArray();
  42. for (int i = 0; i < ch.Length; i++)
  43. {
  44. if (ch[i] >= '0' && ch[i] <= '9')
  45. {
  46. //数字用红色显示
  47. g.DrawString(ch[i].ToString(), f, r, 3 + (i * 12), 3);
  48. }
  49. else
  50. { //字母用黑色显示
  51. g.DrawString(ch[i].ToString(), f, b, 3 + (i * 12), 3);
  52. }
  53. }
  54. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  55. image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  56. //history back 不重复
  57. pictureBox1.Image = image;
  58. #endregion
  59.  
  60. }

点击事件调用:

  1. CreateVerificationCode(4); //4表示产生四位数验证码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值