有时候在网页中登录时需要输入验证码,C#中也可以做到,以下是两种不同的方式:
第一种方式:
- private void button1_Click(object sender, EventArgs e)
- {
- if (textBox3.Text != label4.Text) //验证码输入有误
- {
- MessageBox.Show("验证码输入错误!!!");
- Random rnd = new Random();
- //生成验证码
- this.label4.Text = rnd.Next(1000, 9999).ToString(); //验证码取值范围
- }
- else
- {
- if (radioButton1.Checked) //管理员登录
- {
- if (textBox1.Text == "admin" && textBox2.Text == "admin")
- {
- Admin frm = new Admin();
- frm.Show();
- this.Hide();
- }
- else
- {
- MessageBox.Show("密码错误或者该用户不存在!!!");
- textBox1.Text = "";
- textBox2.Text = "";
- textBox3.Text = "";
- }
- }
- }
- }
第二种方式:(推荐使用第一种,简单高效)
- private void CreateVerificationCode(int CodeCount)
- {
- #region 产生验证码
- 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";
- string[] allCharArray = allChar.Split(',');
- string RandomCode = "";
- int temp = -1;
- Random rand = new Random();
- for (int i = 0; i < CodeCount; i++)
- {
- if (temp != -1)
- {
- rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
- }
- int t = rand.Next(33);
- while (temp == t)
- {
- t = rand.Next(33);
- }
- temp = t;
- RandomCode += allCharArray[t];
- }
- checkCode = RandomCode;
- #endregion
- #region 绘制验证码
- int iwidth = (int)(checkCode.Length * 14);
- System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 21);
- Graphics g = Graphics.FromImage(image);
- Font f = new System.Drawing.Font("Arial ", 10);//, System.Drawing.FontStyle.Bold);
- Brush b = new System.Drawing.SolidBrush(Color.Black);
- Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));
- g.Clear(System.Drawing.ColorTranslator.FromHtml("#99C1CB"));//背景色
- char[] ch = checkCode.ToCharArray();
- for (int i = 0; i < ch.Length; i++)
- {
- if (ch[i] >= '0' && ch[i] <= '9')
- {
- //数字用红色显示
- g.DrawString(ch[i].ToString(), f, r, 3 + (i * 12), 3);
- }
- else
- { //字母用黑色显示
- g.DrawString(ch[i].ToString(), f, b, 3 + (i * 12), 3);
- }
- }
- System.IO.MemoryStream ms = new System.IO.MemoryStream();
- image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
- //history back 不重复
- pictureBox1.Image = image;
- #endregion
- }
点击事件调用:
- CreateVerificationCode(4); //4表示产生四位数验证码
亲爱的:若该文章解决了您的问题,可否收藏+评论+分享呢?
文章评论 本文章有个评论