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

一、功能界面

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

图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

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

(0)

相关推荐

  • C#生成验证码图片的方法

    本文实例为大家分享了C#生成验证码图片的具体代码,供大家参考,具体内容如下 /// <summary> /// 生成验证码图片 /// </summary> /// <returns></returns> public byte[] GetVerifyCode() { int codeW = 80; int codeH = 40; int fontSize = 18; string chkCode = string.Empty; //颜色列表,用于验证码.噪

  • c# .net 生成图片验证码的代码

    说明:  .net 万岁...  .net framework 的类库真是太强了, 用 GDI+ 可以干N多N多事情.   广告时间:  shawl.qiu C# CMS 系统 预计40天后开始编码, 现在逐步设计中, 免得到时求职说什么什么作品...唉.  PS: 今天求职真是惨不忍睹, 谁要招网页相关的请联系 13435580019, 邱先生.   什么地方俺都去, 工资只要能过活就行,  但是食宿问题得解决.  shawl.qiu  2007-02-01  http://blog.csdn

  • C#如何消除验证码图片的锯齿效果

    引言 基于生成图片实现了一个手机号转图片的需求. 内容也很简单,直接用手机号生成一个png图片.就是为了背景透明以便其他地方调用. 有无锯齿主要依靠一句代码:g.TextRenderingHint= TextRenderingHint.AntiAlias; 生成图片   1.有锯齿 2.无锯齿 生成方法 string color = "#ff6633"; System.Drawing.Bitmap image = new System.Drawing.Bitmap(170, 35);

  • C#实现截取验证码图片

    本文实例为大家分享了C#截取验证码图片的具体代码,供大家参考,具体内容如下 使用Graphics类中的DrawImage方法,这个方法有30种重载方式,这里只介绍一种,也是我认为最直观的一种,代码如下: using System.Drawing; namespace kq.Utils { public static class CommonTools { public static Bitmap getVerifyCode(Bitmap srcBmp, Rectangle rectangle)

  • c#实现识别图片上的验证码数字

    public void imgdo(Bitmap img) { //去色 Bitmap btp = img; Color c = new Color(); int rr, gg, bb; for (int i = 0; i < btp.Width; i++) { for (int j = 0; j < btp.Height; j++) { //取图片当前的像素点 c = btp.GetPixel(i, j); rr = c.R; gg = c.G; bb = c.B; //改变颜色 if (r

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

    一.功能界面 图1 验证码(区分大小写) 图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 S

  • node+vue前后端分离实现登录时使用图片验证码功能

    目录 后端代码 前端代码 获取验证码方法 登录验证方法 记录一下前端使用验证码登录的过程后端用的是node.js,关键模块是svg-captcha前端使用的是vue2最后的登录界面如下: 后端代码 先上代码,然后解释 const svgCaptcha = require('svg-captcha') exports.checkCode = (req, res) => { const img = svgCaptcha.create({ size: 4, ignoreChars: '0o1l', c

  • django项目登录中使用图片验证码的实现方法

    应用下创建untils文件夹放置封装图片验证码的函数 创建validCode.py文件定义验证码规则 import random def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) def get_valid_code_img(request): # 方式: from PIL import Image, ImageDraw, ImageFon

  • 用python登录带弱图片验证码的网站

    上一篇介绍了使用python模拟登陆网站,但是登陆的网站都是直接输入账号及密码进行登陆,现在很多网站为了加强用户安全性和提高反爬虫机制都会有包括字符.图片.手机验证等等各式各样的验证码.图片验证码就是其中一种,而且识别难度越来越大,人为都比较难识别.本篇我们简单介绍一下使用python登陆带弱图片验证码的网站. 图片验证码 一般都通过加干扰线.粘连或扭曲等方式来增加强度. 登陆 我们选择一个政务网站(图片验证码的强度较低). 点击个人用户登录 访问网站首页以后我们发现需要先点击个人用户登陆,且元

  • vue实现登录时的图片验证码

    本文实例为大家分享了vue实现登录时的图片验证码的具体代码,供大家参考,具体内容如下 效果图 一.新建vue组件components/identify/identify.vue <template> <div class="s-canvas"> <canvas id="s-canvas" :width="contentWidth" :height="contentHeight"></c

  • python自动化实现登录获取图片验证码功能

    主要记录一下:图片验证码 1.获取登录界面的图片 2.获取验证码位置 3.在登录页面截取验证码保存 4.调用百度api识别(目前准确率较高的识别图片api) 本次登录的系统页面,可以看到图片验证码的位置 from selenium import webdriver import time from PIL import Image base_url = '***********' browser = webdriver.Chrome() browser.maximize_window() bro

  • Vue 实现登录界面验证码功能

    登录界面 SIdentify 创建验证码组件,实现绘画出图片验证码 <template> <div class="s-canvas"> <canvas id="s-canvas" :width="contentWidth" :height="contentHeight"></canvas> </div> </template> <script>

  • C# WinForm制作登录界面的实现步骤

    在[解决方案资源管理器]中找到Form1.cs,单击,快捷键F2重命名为“Login.cs”(命名很重要,不然之后项目多了根据不知道哪个项目的内容是什么) 对窗体[Text]属性.[size]属性和[FormBoardStyle]属性进行修改 添加一个新的窗体 Ctrl+Shift+A,在弹出框中选择[Windows窗体],命名为main.cs 取消登录界面最大化最小化关闭按钮在父窗体菜单栏上显示最大化:MaximizeBox,最小化:MinimizeBox如果设置一个为False 的时候会显示

  • springboot登陆页面图片验证码简单的web项目实现

    写在前面 前段时间大家都说最近大环境不好,好多公司在裁员,换工作的话不推荐轻易的裸辞,但是我想说的是我所在的公司好流弊,有做不完的业务需求,还有就是招不完的人...... 最近我也是比较繁忙,但是还是要抽一点时间来进行自我复盘和记录,最近也写一个简单的小功能,就是登陆界面的图片验证码功能 环境:Tomcat9.Jdk1.8 1 生成验证码的工具类 public class RandomValidateCodeUtil { public static final String RANDOMCODE

  • Selenium+Python 自动化操控登录界面实例(有简单验证码图片校验)

    从最简单的Web浏览器的登录界面开始,登录界面如下: 进行Web页面自动化测试,对页面上的元素进行定位和操作是核心.而操作又是以定位为前提的,因此,对页面元素的定位是进行自动化测试的基础. 页面上的元素就像人一样,有各种属性,比如元素名字,元素id,元素属性(class属性,name属性)等等.webdriver就是利用元素的这些属性来进行定位的. 可以用于定位的常用的元素属性: id name class name tag name link text partial link text xp

随机推荐