WinForms 图形验证码更直观,通过 Graphics 绘制字符、干扰线、噪点,提升安全性。
案例:WinForms 图形验证码生成
- 新建 Windows Forms 项目,添加
PictureBox(命名为 pbCaptcha)和Button(命名为 btnRefresh)。 - 代码实现:
using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace WinFormsCaptcha { public partial class Form1 : Form { public Form1() { InitializeComponent(); // 初始化生成验证码 GenerateCaptchaImage(); } // 生成图形验证码 private void GenerateCaptchaImage() { int width = pbCaptcha.Width; int height = pbCaptcha.Height; // 创建位图 using (Bitmap bitmap = new Bitmap(width, height)) using (Graphics g = Graphics.FromImage(bitmap)) { // 设置背景色(浅色) g.Clear(Color.AliceBlue); // 绘制干扰线(5条随机线) Random random = new Random(); Pen pen = new Pen(Color.LightGray, 1); for (int i = 0; i < 5; i++) { int x1 = random.Next(width); int y1 = random.Next(height); int x2 = random.Next(width); int y2 = random.Next(height); g.DrawLine(pen, x1, y1, x2, y2); } // 绘制噪点(100个随机点) for (int i = 0; i < 100; i++) { int x = random.Next(width); int y = random.Next(height); bitmap.SetPixel(x, y, Color.FromArgb(random.Next(256), random.Next(256), random.Next(256))); } // 生成4位验证码 string captcha = GenerateCaptchaText(4); // 存储验证码(用于后续验证) pbCaptcha.Tag = captcha; // 绘制验证码文字(随机字体、颜色、位置) Font font = new Font("Arial", 20, FontStyle.Bold | FontStyle.Italic); Brush[] brushes = { Brushes.Red, Brushes.Blue, Brushes.Green, Brushes.Orange }; for (int i = 0; i < captcha.Length; i++) { // 每个字符随机颜色、轻微旋转 Brush brush = brushes[random.Next(brushes.Length)]; float angle = random.Next(-15, 15); // 旋转角度 g.TranslateTransform(width / 4 * i + 10, height / 2); g.RotateTransform(angle); g.DrawString(captcha[i].ToString(), font, brush, 0, 0); g.RotateTransform(-angle); g.TranslateTransform(-(width / 4 * i + 10), -height / 2); } // 设置图片到PictureBox pbCaptcha.Image = new Bitmap(bitmap); } } // 生成验证码文本(字母+数字) private string GenerateCaptchaText(int length) { string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random random = new Random(); char[] captchaChars = new char[length]; for (int i = 0; i < length; i++) { captchaChars[i] = chars[random.Next(chars.Length)]; } return new string(captchaChars); } // 刷新验证码按钮点击事件 private void btnRefresh_Click(object sender, EventArgs e) { GenerateCaptchaImage(); } // 验证按钮点击事件(可添加TextBox输入验证) private void btnVerify_Click(object sender, EventArgs e) { string input = txtInput.Text.Trim(); string captcha = pbCaptcha.Tag.ToString(); if (string.Equals(input, captcha, StringComparison.OrdinalIgnoreCase)) { MessageBox.Show("验证码正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("验证码错误!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); GenerateCaptchaImage(); // 错误后刷新验证码 txtInput.Clear(); } } } }
功能说明:支持刷新验证码、干扰线 + 噪点防破解、字符旋转 + 随机颜色,用户输入后验证。