WinForms 验证码类的实现

1. 验证码工具类 (CaptchaGenerator.cs)

cs 复制代码
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Windows.Forms;

namespace SimpleCaptcha
{
    public class CaptchaGenerator
    {
        private string _captchaText;
        private Bitmap _captchaImage;

        public string GenerateCaptcha()
        {
            _captchaText = GenerateRandomString(4);
            _captchaImage = CreateCaptchaImage(_captchaText);
            return _captchaText;
        }

        public Bitmap GetCaptchaImage() => _captchaImage;
        
        public bool Verify(string userInput) => 
            string.Equals(_captchaText, userInput, StringComparison.OrdinalIgnoreCase);

        private string GenerateRandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var random = new Random();
            return new string(
                Enumerable.Repeat(chars, length)
                          .Select(s => s[random.Next(s.Length)])
                          .ToArray());
        }

        private Bitmap CreateCaptchaImage(string captchaText)
        {
            var size = new Size(120, 40);
            var bitmap = new Bitmap(size.Width, size.Height);
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.Clear(Color.White);
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                
                var font = new Font("Arial", 14, FontStyle.Bold);
                var brush = new SolidBrush(Color.Black);
                
                // 绘制验证码文本
                graphics.DrawString(captchaText, font, brush, 0, 0);
                
                // 添加干扰线
                using (var pen = new Pen(Color.LightGray, 1))
                {
                    for (int i = 0; i < 3; i++)
                    {
                        graphics.DrawLine(pen, 
                            new Point(0, new Random().Next(size.Height)), 
                            new Point(size.Width, new Random().Next(size.Height)));
                    }
                }
            }
            return bitmap;
        }
    }
}

2. 主窗体实现 (MainForm.cs)

cs 复制代码
using System;
using System.Drawing;
using System.Windows.Forms;

namespace SimpleCaptcha
{
    public partial class MainForm : Form
    {
        private CaptchaGenerator _captchaGenerator = new CaptchaGenerator();
        private string _currentCaptcha;

        public MainForm()
        {
            InitializeComponent();
            SetupCaptcha();
        }

        private void SetupCaptcha()
        {
            // 生成验证码
            _currentCaptcha = _captchaGenerator.GenerateCaptcha();
            
            // 显示验证码
            pictureBoxCaptcha.Image = _captchaGenerator.GetCaptchaImage();
            
            // 点击图片刷新验证码
            pictureBoxCaptcha.Click += (s, e) => RefreshCaptcha();
        }

        private void RefreshCaptcha()
        {
            _currentCaptcha = _captchaGenerator.GenerateCaptcha();
            pictureBoxCaptcha.Image = _captchaGenerator.GetCaptchaImage();
            textBoxCaptcha.Text = string.Empty;
            textBoxCaptcha.Focus();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBoxCaptcha.Text))
            {
                MessageBox.Show("请输入验证码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (_captchaGenerator.Verify(textBoxCaptcha.Text))
            {
                MessageBox.Show("验证码正确!登录成功!", "验证成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("验证码错误,请重试!", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                RefreshCaptcha();
            }
        }

        private void InitializeComponent()
        {
            // 创建控件
            pictureBoxCaptcha = new PictureBox { Size = new Size(120, 40), BorderStyle = BorderStyle.FixedSingle };
            textBoxCaptcha = new TextBox { Size = new Size(120, 20), Location = new Point(10, 50) };
            btnLogin = new Button { Text = "登录", Size = new Size(120, 30), Location = new Point(10, 80) };

            // 设置窗体
            Text = "验证码登录";
            Size = new Size(150, 130);
            StartPosition = FormStartPosition.CenterScreen;
            
            // 添加控件
            Controls.Add(pictureBoxCaptcha);
            Controls.Add(textBoxCaptcha);
            Controls.Add(btnLogin);

            // 事件绑定
            btnLogin.Click += btnLogin_Click;
        }

        // 窗体控件
        private PictureBox pictureBoxCaptcha;
        private TextBox textBoxCaptcha;
        private Button btnLogin;
    }
}

3. 使用说明

  1. 创建新项目

    • 在Visual Studio中创建新的WinForms项目
    • 添加CaptchaGenerator.csMainForm.cs文件
  2. 启动应用程序

    • 运行应用程序,会显示一个验证码图片和输入框
    • 点击验证码图片即可刷新验证码
    • 在输入框中输入验证码,点击"登录"按钮进行验证
  3. 关键特性

    • ✅ 点击图片刷新验证码(无需额外按钮)
    • ✅ 简洁的界面(仅需3个控件)
    • ✅ 自动清空输入框
    • ✅ 验证码区分大小写(但验证时忽略大小写)
    • ✅ 添加了干扰线提高安全性

4. 效果图

复制代码
+---------------------+
|        [验证码]     |  <- 点击这里刷新
+---------------------+
|      输入验证码     |
+---------------------+
|      [登录按钮]     |
+---------------------+

5. 为什么这样设计

  1. 极简设计:只保留必需的控件(图片、输入框、登录按钮)
  2. 用户体验:点击验证码图片即可刷新,无需额外操作
  3. 代码简洁:总代码量仅约70行,易于理解和维护
  4. 安全性:添加了干扰线,使验证码更难被OCR识别
  5. 即时反馈:验证失败时自动刷新验证码

6. 运行效果

  1. 应用启动后显示随机验证码
  2. 点击验证码图片 -> 验证码刷新
  3. 输入正确验证码 -> 显示登录成功
  4. 输入错误验证码 -> 显示错误并自动刷新验证码
相关推荐
我本梁人2 小时前
Winform实现多语言切换
winform
武藤一雄2 小时前
告别繁琐的 out 参数:C# 现代元组(ValueTuple)如何重构你的方法返回值
microsoft·c#·asp.net·.net·.netcore
曹牧3 小时前
C#:线程中实现延时等待
开发语言·c#
长不大的小Tom3 小时前
从0开始入门WPF(开发环境搭建)
c#
阿蒙Amon3 小时前
C#常用类库-详解Log4Net
开发语言·c#
唐青枫4 小时前
C#.NET Memory 深入解析:跨异步边界的内存视图与高性能实战
c#·.net
缺点内向4 小时前
.NET办公自动化教程:Spire.XLS操作Excel——导出TXT格式详解
c#·自动化·.net·excel
落叶@Henry4 小时前
C# async 和await 的面试题
开发语言·c#
人工智能AI技术5 小时前
C#接入CodeBuddy CLI实战:在.NET后端集成多AI Provider的全流程拆解
人工智能·c#