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.cs和MainForm.cs文件
  2. 启动应用程序:

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

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

4. 效果图

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

5. 为什么这样设计

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

6. 运行效果

  1. 应用启动后显示随机验证码
  2. 点击验证码图片 -> 验证码刷新
  3. 输入正确验证码 -> 显示登录成功
  4. 输入错误验证码 -> 显示错误并自动刷新验证码
相关推荐
zdr尽职尽责1 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
BruceNeter2 天前
C# winform卡死问题分析1——线程池子线程创建句柄
c#·.net
何以解忧唯有撸码4 天前
开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
c#·winform·自定义控件·gdi
国家一级摸鱼选手4 天前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
汤姆宝库5 天前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
Risehuxyc5 天前
C# 发展历史
开发语言·c#
kyle~5 天前
C# --- 反射
开发语言·c#
暴走约伯6 天前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
用户788477316347 天前
WinForms 迁移 WPF:Upgrade Assistant 覆盖 30%,剩下 70% 我手写了六周
c#
寂寞的船7 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua