winform+GDI画验证码

winform+GDI画验证码

设计界面:

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _01服务器生成验证码
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetCode(4);
        }
        Random r = new Random();
        string code;
        private void SetCode(int length)
        {
            code = "";
            for (int i = 0; i < length; i++)
            {
                int type = r.Next(0, 2);
                if (type==0)
                {
                    code += r.Next(0, 10);
                }
                else if (type==1)
                {
                    code += (char)r.Next(97, 123);
                }
            }
            if (string.IsNullOrWhiteSpace(code))
            {
                return;
            }

            Bitmap img = new Bitmap(code.Length*15+10,25);
            Graphics graphics = Graphics.FromImage(img);
            graphics.Clear(Color.White);
            Pen pen = new Pen(Color.Black,1);
            graphics.DrawRectangle(pen,0,0,img.Width-1,img.Height-1);
            for (int i = 0; i < code.Length; i++)
            {
                Pen p = new Pen(Color.FromArgb(r.Next(255), r.Next(255), r.Next(255)),r.Next(2,4));
                graphics.DrawLine(p,r.Next(0,img.Width),r.Next(0,img.Height), r.Next(0, img.Width), r.Next(0, img.Height));
            }
            graphics.DrawString(code, new Font("宋体", 15, FontStyle.Bold| FontStyle.Italic), new SolidBrush(Color.Black), new Point(10, 5));
            for (int i = 0; i < code.Length*20; i++)
            {
                graphics.FillEllipse(new SolidBrush(Color.FromArgb(r.Next(255), r.Next(255), r.Next(255))), r.Next(0, img.Width), r.Next(0, img.Height),2,2);
            }
            pictureBox1.Image = img;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            SetCode(4);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (code.ToUpper().Equals(textBox1.Text.ToUpper()))
            {
                MessageBox.Show("正确");
            }
            else
            {
                MessageBox.Show("验证码错误");
                SetCode(4);
            }
        }
    }
}

运行结果:

在这里插入图片描述

发布了96 篇原创文章 · 获赞 147 · 访问量 9842

猜你喜欢

转载自blog.csdn.net/chonbi/article/details/103753694