一 界面效果 用个pictureBox控件 来显示 验证码
二 定义个方法 确定 验证码的 范围和个数
View Code
/// <summary> /// 产生验证码,参数为需要产生的验证码的字符个数 /// </summary> /// <param name="codeLength"></param> /// <returns></returns> public string CreateCode(int codeLength) { string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; string[] strArr = so.Split(','); string code = ""; Random rand = new Random(); //控制 验证码的个数 for (int i = 0; i < codeLength; i++) { code+=strArr[rand.Next(0,strArr.Length)]; } return code; } #endregion
三 定义个方法 确定 随机获取 图片
View Code
public Bitmap CreateImage(string code) { //处理由像素数据定义的图像的对象 //用指定的大小初始化 System.Drawing.Bitmap 类的新实例。 //width 120新 System.Drawing.Bitmap 的宽度(以像素为单位)。 //height:40 新 System.Drawing.Bitmap 的高度(以像素为单位)。 Bitmap image = new Bitmap(120, 40); // 封装一个 GDI+ 绘图图面 Graphics g = Graphics.FromImage(image); // 定义的颜色名称或 RGB 颜色值与 System.Drawing.Color 对象之间相互转换 //需要引入 using System.Web.UI.WebControls; 命名空间 WebColorConverter ww = new WebColorConverter(); g.Clear((Color)ww.ConvertFromString("#FAE264")); Random random = new Random(); //画图片的背景噪音线 for (int j = 0; j < 12; j++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(Pens.LightGray, x1, y1, x2, y2); } //输出不同字体和颜色的验证码字符 for (int i = 0; i < code.Length; i++) { int findex = random.Next(3); int cindex = random.Next(7); string[] font = new string[3] { "Arial", "Impact", "Showcard Gothic" }; Color[] c = new Color[7] { Color.FromArgb(100, 100, 100), Color.FromArgb(0, 0, 255), Color.FromArgb(255, 100, 100) , Color.FromArgb(255,0,0), Color.FromArgb(0,255,0), Color.FromArgb(255,100,255), Color.FromArgb(255,0,255) }; // 指定的大小和样式初始化 Font f = new Font(font[findex], 20, FontStyle.Bold); SolidBrush b = new SolidBrush(c[cindex]); int ii = 4; if ((i + 1) % 2 == 0) { f = new Font(font[findex], 20, FontStyle.Bold | FontStyle.Italic); ii = 2; } g.DrawString(code.Substring(i, 1), f, b, 20 + (i * 14), ii); } //画图片的边框线 // g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); Bitmap bm = new Bitmap(ms); g.Dispose(); image.Dispose(); return bm; }
四 看不清 换一张
View Code
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { generatecode(); }
五 点击button 验证 验证码 是否正确
View Code
#region 验证码 为空验证 if (this.textBox3.Text.ToString() != code.ToLower()) { RadMessageBox.Show(null, "验证信息输入有误,请重新输入!", "提示信息"); this.textBox3.Text = ""; this.textBox3.Focus(); } else RadMessageBox.Show(null, "验证right","提示信息");
六 页面加载
View Code
generatecode(); this.BackColor = Color.FromArgb(191, 219, 255);