欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# WinForm 登录界面的图片验证码(区分大小写+不区分大小写)

程序员文章站 2022-06-29 22:39:07
一、功能界面 图1 验证码(区分大小写)图2 验证码(不区分大小写) 二、创建一个产生验证码的类class1(1)生成随机验证码字符串,用的是random随机函数(2)创建验证码图片,将该字符串画在p...

一、功能界面

C# WinForm 登录界面的图片验证码(区分大小写+不区分大小写)

图1 验证码(区分大小写)

C# WinForm 登录界面的图片验证码(区分大小写+不区分大小写)

图2 验证码(不区分大小写)

二、创建一个产生验证码的类class1

(1)生成随机验证码字符串,用的是random随机函数
(2)创建验证码图片,将该字符串画在picturebox控件中

class1.cs:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using system.drawing;//图片
using system.windows.forms;

namespace validcodetest
{
  public class class1
  {
    #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 - 1, 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 system.drawing.font(font[findex], 13, system.drawing.fontstyle.bold);//字体样式(参数2为字体大小)
          brush b = new system.drawing.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)
      {
        messagebox.show("验证码图片创建错误");
      }
    }
    #endregion
  }
}

三、调用

(1)更新验证码
(2)验证(区分大小写)
(3)验证(不区分大小写)

form1.cs:

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;
using validcodetest;

namespace validcode
{
  public partial class form1 : form
  {
    public form1()
    {
      initializecomponent();
    }


    #region 验证码
    private const int validcodelength = 4;//验证码长度    
    private string strvalidcode = "";//验证码            

    //调用自定义函数,更新验证码
    private void updatevalidcode()
    {
      strvalidcode = class1.createrandomcode(validcodelength);//生成随机验证码
      if (strvalidcode == "") return;
      class1.createimage(strvalidcode, pbox1);//创建验证码图片
    }
    #endregion


    private void pbox1_click(object sender, eventargs e)
    {
      updatevalidcode();//点击更新验证码
    }


    private void form1_load(object sender, eventargs e)
    {
      updatevalidcode();//加载更新验证码
    }


    /// <summary>
    /// 验证(区分大小写)
    /// </summary>    
    private void btn1_click(object sender, eventargs e)
    {
      string validcode = txtvalidcode.text.trim();

      char[] ch1 = validcode.tochararray();
      char[] ch2 = strvalidcode.tochararray();
      int count1 = 0;//字母个数
      int count2 = 0;//数字个数

      if (string.isnullorempty(validcode) != true)//验证码不为空
      {
        for (int i = 0; i < strvalidcode.length; i++)
        {
          if ((ch1[i] >= 'a' && ch1[i] <= 'z') || (ch1[i] >= 'a' && ch1[i] <= 'z'))//字母
          {
            if (ch1[i] == ch2[i])
            {
              count1++;
            }
          }
          else//数字
          {
            if (ch1[i] == ch2[i])
            {
              count2++;
            }
          }

        }

        int countsum = count1 + count2;
        if (countsum == strvalidcode.length)
        {
          messagebox.show("验证通过", "提示", messageboxbuttons.ok, messageboxicon.information);
          updatevalidcode();
          txtvalidcode.text = "";
          txtvalidcode.focus();
        }
        else
        {
          messagebox.show("验证失败", "警告", messageboxbuttons.ok, messageboxicon.exclamation);
          updatevalidcode();//更新验证码
          txtvalidcode.text = "";
          txtvalidcode.focus();
        }
      }
      else//验证码为空
      {
        messagebox.show("请输入验证码", "提示", messageboxbuttons.ok, messageboxicon.information);
        updatevalidcode();//更新验证码
        txtvalidcode.text = "";
        txtvalidcode.focus();
      }
    }


    /// <summary>
    /// 验证(不区分大小写)
    /// </summary> 
    private void btn2_click(object sender, eventargs e)
    {
      string validcode = txtvalidcode.text.trim();

      if (string.isnullorempty(validcode) != true)//验证码不为空
      {
        if (validcode.tolower() == strvalidcode.tolower())
        {
          messagebox.show("验证通过", "提示", messageboxbuttons.ok, messageboxicon.information);
          updatevalidcode();
          txtvalidcode.text = "";
          txtvalidcode.focus();
        }
        else
        {
          messagebox.show("验证失败", "警告", messageboxbuttons.ok, messageboxicon.exclamation);
          updatevalidcode();//更新验证码
          txtvalidcode.text = "";
          txtvalidcode.focus();
        }
      }
      else//验证码为空
      {
        messagebox.show("请输入验证码", "提示", messageboxbuttons.ok, messageboxicon.information);
        updatevalidcode();//更新验证码
        txtvalidcode.text = "";
        txtvalidcode.focus();
      }
    }
  }
}

.exe测试文件下载: validcode_jb51.zip

参考文章:
https://www.jianshu.com/p/d89f22cf51bf

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。