Winform实现验证码功能

介绍下Winform实现验证码的步骤:

首先拖入控件:PictureBox显示验证码;TextBox输入验证码;Check按钮;Label标签-点击更换验证码;

1.随机产生一个4位的字符串,由数字,大小写字母组成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string RandomCode()
{
    string retCode = "";
    for (int i = 0; i < 4; i++)
    {
        while (true)
        {
            int id = rd.Next(48, 122);
            if (id >= 48 && id <= 57 || id >= 65 && id <= 90 || id >= 97 && id <= 122)
            {
                retCode += Convert.ToChar(id).ToString();
                break;
            }
        }
    }
    return retCode;
}

2.创建画板:

1
2
3
Bitmap bMap = new Bitmap(this.pictureBox1.Width,this.pictureBox1.Height);
Graphics g = Graphics.FromImage(bMap);
g.Clear(Color.LightGray);

3.在画板上画几条颜色随机的线条:

1
2
3
4
5
6
7
8
for (int i = 0; i < 8; i++)
{
    int x1 = rd.Next(bMap.Width);
    int y1 = rd.Next(bMap.Height);
    int x2 = rd.Next(bMap.Width);
    int y2 = rd.Next(bMap.Height);
    g.DrawLine(new Pen(Color.FromArgb(rd.Next())), x1, y1, x2, y2);
}

4.画一些背景噪点,颜色随机:

1
2
3
4
5
6
for (int i = 0; i < 600; i++)
{
    int x = rd.Next(this.pictureBox1.Width);
    int y = rd.Next(this.pictureBox1.Height);
    bMap.SetPixel(x, y, Color.FromArgb(rd.Next()));
}

5.画验证码:

1
2
3
4
5
6
7
Font ft = new Font("宋体", 24, FontStyle.Bold | FontStyle.Italic);
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(
    new Rectangle(0, 0, bMap.Width, bMap.Height), Color.OrangeRed, Color.DarkOrchid, 1.2f, true);
for (int i = 0; i < codeStr.Length; i++)
{
    g.DrawString(codeStr[i].ToString(), ft, brush, 5 + 23 * i, -1);
}

6.将画好的图像赋给PictureBox:

1
2
3
this.pictureBox1.Image = bMap;
g.Dispose();
ft.Dispose();

7.按钮点击事件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private void Form1_Load(object sender, EventArgs e)
{
    rd = new Random();
    CreateCodeImage(checkCode = RandomCode());
}
 
private void label1_Click(object sender, EventArgs e)
{
    CreateCodeImage(checkCode = RandomCode());
}
 
private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text != checkCode)
    {
        MessageBox.Show("验证失败,请重新输入", "提示");
        CreateCodeImage(checkCode = RandomCode());
    }
    else
        MessageBox.Show("验证通过", "提示");
}

x效果展示:

 

 

  

  

  

  

  

  

  

posted @   [春风十里]  阅读(314)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示