1. 程式人生 > 程式設計 >C# WinForm 登入介面的圖片驗證碼(區分大小寫+不區分大小寫)

C# WinForm 登入介面的圖片驗證碼(區分大小寫+不區分大小寫)

一、功能介面

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),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,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("驗證失敗","警告",MessageBoxIcon.Exclamation);
          UpdateValidCode();//更新驗證碼
          txtValidCode.Text = "";
          txtValidCode.Focus();
        }
      }
      else//驗證碼為空
      {
        MessageBox.Show("請輸入驗證碼",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("驗證通過",MessageBoxIcon.Information);
        UpdateValidCode();//更新驗證碼
        txtValidCode.Text = "";
        txtValidCode.Focus();
      }
    }
  }
}

.exe測試檔案下載: ValidCode_jb51.zip

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。