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. 输入错误验证码 -> 显示错误并自动刷新验证码
相关推荐
fie88894 小时前
C# 文件分割与合并工具设计与实现
开发语言·c#
ytttr8736 小时前
C# 读取数据库表结构工具设计与实现
开发语言·数据库·c#
鸽子一号6 小时前
c#笔记之lambda表达式和linq
笔记·c#·linq
qq_391105347 小时前
TDengine C# 连接示例和授权管理
大数据·数据库·c#·时序数据库·tdengine
a17798877128 小时前
小程序码的生成与获取码中的scene
小程序·c#
无风听海8 小时前
.NET10之C# Target-typed new expression深入解析
windows·c#·.net
这辈子谁会真的心疼你9 小时前
怎么修改pdf文档属性?介绍三个方法
数据库·pdf·c#
初九之潜龙勿用1 天前
C# 解决“因为算法不同,客户端和服务器无法通信”的问题
服务器·开发语言·网络协议·网络安全·c#
net3m331 天前
C#插件化架构(Plugin Architecture)或 可插拔架构,根据产品类型编码的不同自动路由到目标函数,而无需为每个产品都编码相应的代码!!
重构·c#
水深00安东尼1 天前
C#猜数字小游戏
开发语言·c#