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;
namespace WindowsFormsApp11
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
///
/// 刷新按钮
///
///
///
private void button1_Click(object sender, EventArgs e)
{
//刷新验证码
CodeImage(CheckCode());
}
///
/// 生成验证码
///
///
private string CheckCode()
{
int number;
char code;
string checkCode = string.Empty; //声明变量存储随机生成的4位英文或数字
Random random = new Random(); //生成随机数
for (int i = 0; i < 4; i++)
{
number = random.Next(); //返回非负随机数
if (number % 2 == 0) //判断数字是否为偶数
{
code = (char)('0' + (char)(number % 10)); //产生随机数
}
else //非偶数时处理
{
code = (char)('A' + (char)(number % 26)); // 产生随机字母
}
checkCode += " " + code.ToString(); //累加字符串
}
return checkCode; //返回生成的字符串
}
///
/// 将生成的随机验证码绘制成图片,并显示在PictueBox控件上
///
///
private void CodeImage(string checkCode)
{
///生成验证码
if (checkCode == null || checkCode.Trim() == String.Empty)
{
return;
}
Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 9.5)), 22);
Graphics g = Graphics.FromImage(image); //创建Graphics对象
try
{
Random random = new Random(); //生成随机生成器
g.Clear(Color.White); //清空图片背景色
for (int i = 0; i < 3; i++) //画3条线 图片背景噪音线
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
//int x2 = x1 + 20;
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
//int y2 = y1 + 20;
g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
}
Font = new Font("Arial",12,(FontStyle.Bold)); //设置验证码字体和大小
g.DrawString(checkCode,Font,new SolidBrush(Color.Red),2,2); //把字体内容画到图片上
for (int i = 0; i < 150; i++) //画图片的前景噪音点
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
//设置图片
this.pictureBox1.Width = image.Width; //设置picturebox的宽度
this.pictureBox1.Height = image.Height; //设置PictureBox的高度
this.pictureBox1.BackgroundImage = image; //设置PicetureBox的背景图像
}
catch (Exception ex)
{
MessageBox.Show("错误"+ex.Message);
}
}
//首次打开窗口时加载验证码图片
private void Form2_Load(object sender, EventArgs e)
{
CodeImage(CheckCode()); //生成验证码
}
//退出
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}