2024年6月14日发(作者:)

1 动态绘制验证码

实验示例1-9:设计如图1-11所示程序,能动态生成验证码。控件相关属性及事

件如下表1-9所示:

表1-9 控件属性设置及事件介绍

控件 名称

Form Form1

GroupBox groupBox1

PictureBox pictureBox1

btnother

Button

btnexit

属性值

Text=动态验证码

Text=验证码

事件

Click

Click

备注

图1-11 动态验证码

主要代码:

public partial class Form1 : Form

{

private const int codelength = 6;

private string randomcode = "";

public Form1()

{

InitializeComponent();

}

//生成一定长度的验证码

private string CreateRandomeCode(int length)

{

int rand;

char code;

string randomcode = ;

random = new Random();

for (int i = 0; i < length; i++)

{

rand = ();

if (rand % 3 == 0)

code = (char)('A' + (char)(rand % 26));

else

{

code = (char)('0' + (char)(rand % 10));

}

randomcode += ng();

}

return randomcode;

}

//创建随机码图片

private void createimage(string randomcode)

{

if(randomcode==null || ()==)

{

return;

}

image = new Bitmap((int)g( *

35.0), 75);

Graphics g = age(image);

try

{

//绘制边框

int randAngle = 30;

();

ctangle(new Pen(, 0), 0, 0, - 1, -

1);

ingMode = ias;

Random rand = new Random();

//背景噪点生成

Pen blackPen = new Pen(lue, 0);

for (int i = 0; i < 50; i++)

{

int x = (0, );

int y = (0, );

ctangle(blackPen, x, y, 1, 1);

}

char[] chars = Array(); //拆散字符串成单个字符数组

//定义文字居中

StringFormat format = new StringFormat();

ent = ;

ignment = ;

//定义颜色

Color[] c = { , , een, htBlue,

, };

//定义字体

string[] font = { "Microsoft Sans Serif", "Arial", "宋体" };

for (int i = 0; i < ; i++)

{

int cindex = (6);

int findex = (3);

Font f = new Font(font[findex], 30, );

Brush b = new rush(c[cindex]);

Point dot = new Point(25, 25);

float angle = (-randAngle, randAngle);

ateTransform(dot.X, dot.Y);

Transform(angle);

ring(chars[i].ToString(), f, b, 1, 1, format);

Transform(-angle);

ateTransform(2, -dot.Y);

}

= ;

= ;

oundImage = image;

}

catch (ArgumentException)

{

("创建图片错误");

}

}

private void Form1_Load(object sender, EventArgs e)

{

randomcode = CreateRandomeCode(codelength);

createimage(randomcode);

}

private void btnother_Click(object sender, EventArgs e)

{

randomcode = CreateRandomeCode(codelength);

createimage(randomcode);

}

}

关键技术:

1. 一定长度随机字符串的获取;

2. 随机字符串的绘制。

2:结合实验示例1-4、示例1-9,设计如图1-12所示登陆

程序。

图1-12 带验证码登陆程序