Winform中实现登录页面跳转以及字母数字验证码功能

场景

Winform中实现简单的登录成功后跳转到主页面的逻辑:

Winform中实现简单的登录成功后跳转到主页面的逻辑_winform登陆界面跳转主页面_霸道流氓气质的博客-CSDN博客

Winform中实现中文验证码(附代码下载):

Winform中实现中文验证码(附代码下载)_霸道流氓气质的博客-CSDN博客

在上面实现登录页面跳转和添加中文验证码的基础上,实现英文和字母的验证码验证。

 

注:

博客:
霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主

实现

1、新建登录窗体并添加如下控件

 

其中显示验证码的是pictureBox控件。

2、修改项目的Program.cs

            Login login = new Login();
            if (login.ShowDialog() == DialogResult.OK) {
                Application.Run(new Form1());
            }

将启动页面改为登录页面Login,Form1为登录成功之后的主页面。

3、新建创建验证码工具类ValidCodeHelper

    public class ValidCodeHelper
    {
        #region 验证码功能           
        /// <summary>
        /// 生成随机验证码字符串
        /// </summary>
        public static string CreateRandomCode(int CodeLength)
        {
            int rand;
            char code;
            string randomCode = String.Empty;//随机验证码

            //生成一定长度的随机验证码      
            //Random random = new Random();//生成随机数对象
            for (int i = 0; i < CodeLength; i++)
            {
                //利用GUID生成6位随机数     
                byte[] buffer = Guid.NewGuid().ToByteArray();//生成字节数组
                int seed = BitConverter.ToInt32(buffer, 0);//利用BitConvert方法把字节数组转换为整数
                Random random = new Random(seed);//以生成的整数作为随机种子
                rand = random.Next();

                //rand = random.Next();    
                if (rand % 3 == 1)
                {
                    code = (char)('A' + (char)(rand % 26));
                }
                else if (rand % 3 == 2)
                {
                    code = (char)('a' + (char)(rand % 26));
                }
                else
                {
                    code = (char)('0' + (char)(rand % 10));
                }
                randomCode += code.ToString();
            }
            return randomCode;
        }

        /// <summary>
        /// 创建验证码图片
        /// </summary>
        public static void CreateImage(string strValidCode, PictureBox pbox)
        {
            try
            {
                int RandAngle = 45;//随机转动角度
                int MapWidth = (int)(strValidCode.Length * 21);
                Bitmap map = new Bitmap(MapWidth, 28);//验证码图片—长和宽

                //创建绘图对象Graphics
                Graphics graph = Graphics.FromImage(map);
                graph.Clear(Color.AliceBlue);//清除绘画面,填充背景色
                graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, map.Width - 3, map.Height - 1);//画一个边框
                graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//模式
                Random rand = new Random();
                //背景噪点生成
                Pen blackPen = new Pen(Color.LightGray, 0);
                for (int i = 0; i < 50; i++)
                {
                    int x = rand.Next(0, map.Width);
                    int y = rand.Next(0, map.Height);
                    graph.DrawRectangle(blackPen, x, y, 1, 1);
                }
                //验证码旋转,防止机器识别
                char[] chars = strValidCode.ToCharArray();//拆散字符串成单字符数组
                //文字居中
                StringFormat format = new StringFormat(StringFormatFlags.NoClip);
                format.Alignment = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;
                //定义颜色
                Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
                //定义字体
                string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
                for (int i = 0; i < chars.Length; i++)
                {
                    int cindex = rand.Next(7);
                    int findex = rand.Next(5);
                    Font f = new Font(font[findex], 13, FontStyle.Bold);//字体样式(参数2为字体大小)
                    Brush b = new SolidBrush(c[cindex]);
                    Point dot = new Point(16, 16);

                    float angle = rand.Next(-RandAngle, RandAngle);//转动的度数
                    graph.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置
                    graph.RotateTransform(angle);
                    graph.DrawString(chars[i].ToString(), f, b, 1, 1, format);

                    graph.RotateTransform(-angle);//转回去
                    graph.TranslateTransform(2, -dot.Y);//移动光标到指定位置
                }
                pbox.Image = map;
            }
            catch (ArgumentException)
            {
               
            }
        }
        #endregion
    }

4、在登录页面窗体的load时间中添加创建验证码

        private void Login_Load(object sender, EventArgs e)
        {
            //生成验证码
            UpdateValidCode();
        }

并且设置pictureBox的点击事件也会重新生成验证码

        private void pictureBox_code_Click(object sender, EventArgs e)
        {
            UpdateValidCode();
        }

生成验证码的实现方法

        private void UpdateValidCode()
        {
            strValidCode = ValidCodeHelper.CreateRandomCode(ValidCodeLength);//生成随机验证码
            if (strValidCode == "") return;
            ValidCodeHelper.CreateImage(strValidCode, pictureBox_code);//创建验证码图片
        }

声明需要用到的类变量

        private const int ValidCodeLength = 4;//验证码长度
                                             
        private String strValidCode = "1234";//验证码 

登录按钮的点击事件进行校验

        private void button_login_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(textBox_username.Text.Trim()))
            {
                MessageBox.Show("用户名不能为空");
            }
            else if (String.IsNullOrEmpty(textBox_password.Text.Trim()))
            {
                MessageBox.Show("密码不能为空");
            }
            else if (String.IsNullOrEmpty(textBox_code.Text.Trim()))
            {
                MessageBox.Show("验证码不能为空");
            }
            else if (!textBox_username.Text.Trim().Equals("自定义用户名"))
            {
                MessageBox.Show("用户名不存在");
            }
            else if (!textBox_password.Text.Trim().Equals("自定义密码"))
            {
                MessageBox.Show("密码不正确");
            }
            else if (!textBox_code.Text.Trim().Equals(strValidCode))
            {
                MessageBox.Show("验证码不正确");
                UpdateValidCode();
            }
            else
            {
                //登录成功,跳转到主页面
                DialogResult = DialogResult.OK;
            }
        }

完整登录页面代码

    public partial class Login : Form
    {


        private const int ValidCodeLength = 4;//验证码长度
                                             
        private String strValidCode = "1234";//验证码  

        public Login()
        {
            InitializeComponent();
        }

        private void button_login_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(textBox_username.Text.Trim()))
            {
                MessageBox.Show("用户名不能为空");
            }
            else if (String.IsNullOrEmpty(textBox_password.Text.Trim()))
            {
                MessageBox.Show("密码不能为空");
            }
            else if (String.IsNullOrEmpty(textBox_code.Text.Trim()))
            {
                MessageBox.Show("验证码不能为空");
            }
            else if (!textBox_username.Text.Trim().Equals("自定义用户名"))
            {
                MessageBox.Show("用户名不存在");
            }
            else if (!textBox_password.Text.Trim().Equals("自定义密码"))
            {
                MessageBox.Show("密码不正确");
            }
            else if (!textBox_code.Text.Trim().Equals(strValidCode))
            {
                MessageBox.Show("验证码不正确");
                UpdateValidCode();
            }
            else
            {
                //登录成功,跳转到主页面
                DialogResult = DialogResult.OK;
            }
        }

        private void Login_Load(object sender, EventArgs e)
        {
            //生成验证码
            UpdateValidCode();
        }

        //调用自定义函数,更新验证码
        private void UpdateValidCode()
        {
            strValidCode = ValidCodeHelper.CreateRandomCode(ValidCodeLength);//生成随机验证码
            if (strValidCode == "") return;
            ValidCodeHelper.CreateImage(strValidCode, pictureBox_code);//创建验证码图片
        }

        //点击图片更新验证码
        private void pictureBox_code_Click(object sender, EventArgs e)
        {
            UpdateValidCode();
        }
    }

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值