C# WINFORM 动态验证码实现

来源:互联网 发布:杭州城市数据大脑 编辑:程序博客网 时间:2024/06/10 13:55



1.随机产生字符串

2.随机设置字符串的显示

3.每隔一秒字符串显示变化

4点击验证码,会产生新的验码


String str = "";//全局变量
        Random r = new Random();//全局对象
        private void pictureBox1_Click(object sender, EventArgs e)//点击验证码,会产生新的验码
        {

            str = null;
            for (int i = 0; i < 5; i++) {
                int rn = r.Next(0, 10);
                str += rn;
            }
           
        }

        private void timer1_Tick(object sender, EventArgs e)//计时器当中去实现。
        {
            Bitmap bmp = new Bitmap(120, 120);
            Graphics g = Graphics.FromImage(bmp);

            for (int i = 0; i < 5; i++)
            {
                String[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "仿宋" };//随机设置字体的样式
                Point p = new Point(i * 15, 0);
                Color[] colors = { Color.Red, Color.Pink, Color.Black, Color.Gray, Color.GreenYellow };//随机设置字体的颜色
                g.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 5)], 20, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 5)]), p);//画图

            }
            for (int i = 0; i < 100;i++ )//画出声燥线

            {
                Point p1 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));
                Point p2 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));
                g.DrawLine(new Pen(Brushes.Green), p1, p2);
            }
            pictureBox1.Image = bmp;
        }

        private void Form1_Load(object sender, EventArgs e)//启动计时器
        {
            timer1.Start();
            for (int i = 0; i < 5; i++)
            {
                int rn = r.Next(0, 10);
                str += rn;
            }
        }

0 0
原创粉丝点击