之前想过写验证的的小程序,一直没写,现在手头项目结项,根据自己的思路快的写了个小的WinForm的验证码程序。代码简单没有多大难度。
frmVerification.cs前台
winform项目中的frmVerification.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 VerificationCode;
namespace VerificationCodeUI
{
public partial class frmVerification : Form
{
CodeImg codeImg;
string strCode;
public frmVerification()
{
InitializeComponent();
codeImg = new CodeImg();
GetCodeImg();
}
private void GetCodeImg()
{
pictureBox1.Image = codeImg.GetCodeImg(4, pictureBox1.Width, pictureBox1.Height, out strCode);
}
private void pictureBox1_Click(object sender, EventArgs e)
{
GetCodeImg();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.ToLower() == strCode.ToLower())
MessageBox.Show("OK");
else
MessageBox.Show("No");
}
}
}
dll项目中的CodeImg.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace VerificationCode
{
public class CodeImg
{
int length;
/// <summary>
/// 长度
/// </summary>
public int Length
{
get { return length; }
set { length = value; }
}
int width;
/// <summary>
/// 宽度
/// </summary>
public int Width
{
get { return width; }
set { width = value; }
}
int height;
/// <summary>
/// 高度
/// </summary>
public int Height
{
get { return height; }
set { height = value; }
}
string code = "";
/// <summary>
/// 验证码
/// </summary>
public string Code
{
get { return code; }
set { code = value; }
}
/// <summary>
/// 随机的字符数组
/// </summary>
string[] seeds={"1","2","3","4","5","6","7","8","9","0",
"A","B","C","D","E","F","G",
"H","I","J","K","L","M","N",
"O","P","Q","R","S","T",
"U","V","W","X","Y","Z",
"a","b","c","d","e","f","g",
"h","i","j","k","l","m","n",
"o","p","q","r","s","t",
"u","v","w","x","y","z"
};
public string[] Seeds
{
get { return seeds; }
set { seeds = value; }
}
public CodeImg()
{
}
public CodeImg(int w,int h)
{
Width = w;
Height = h;
}
public Image GetCodeImg(int length,int w,int h,out string strCode)
{
Random rand;
StringBuilder strbCode=new StringBuilder();
int index=0;
Rectangle rect = new Rectangle(0, 0, w, h);
Bitmap bitMap = new Bitmap(w, h);
Image codeImg = bitMap;
Graphics g = Graphics.FromImage(codeImg);
int fontSize = 16;
Font f = new Font("宋体", fontSize);
SolidBrush s=new SolidBrush(Color.Red);
int x = fontSize + 4;
int y=Convert.ToInt32(Math.Ceiling((decimal)((h - 16) / 2)));
int zeed = 0;
for(int i=0;i<length;i++)
{
zeed = (int)(DateTime.Now.Ticks);
rand = new Random(zeed);
index=rand.Next(Seeds.Length);
strbCode.Append(seeds[index]);
g.DrawString(seeds[index], f, s, x * i, y);
System.Threading.Thread.Sleep(50);
}
strCode = strbCode.ToString();
return codeImg;
}
}
}