110,534
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.pictureBox1.Visible = false;
this.textBox1.GotFocus += new EventHandler(textBox1_GotFocus);
this.textBox1.LostFocus += new EventHandler(textBox1_LostFocus);
this.button1.Focus();
}
void textBox1_LostFocus(object sender, EventArgs e)
{
this.pictureBox1.Visible = false;
}
void textBox1_GotFocus(object sender, EventArgs e)
{
this.pictureBox1.Visible = true;
SetRandomImage();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
SetRandomImage();
}
string checkCode = string.Empty;
private void SetRandomImage()
{
Random randomS = new Random();
int a = randomS.Next(0, 9);
int b = randomS.Next(10, 99);
int c = randomS.Next(100, 999);
checkCode = "";
checkCode = a.ToString() + b.ToString() + c.ToString();
//建立一个位图文件 确立长宽
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 10.5)), 19);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.Wheat );
//画图片的背景噪音线
for (int i = 0; i < 6; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
}
//把产生的随机数以字体的形式写入画面
Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
g.DrawString(checkCode, font, new SolidBrush(Color.Purple ), 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;
this.pictureBox1.Height = image.Height;
this.pictureBox1.Image = image;
}
catch (Exception ex)
{
throw ex;
}
}
private void button1_Click(object sender, EventArgs e)
{
if (checkCode.Equals(this.textBox1.Text))
{
MessageBox.Show("Right!");
}
else
{
MessageBox.Show("Wrong!");
}
}
}