新建一個pictureBox組件,在單擊事件裡寫下相關代碼,實現驗證碼的生成。
代碼如下:
private void pictureBox1_Click(object sender, EventArgs e)
{
Random r = new Random();
string str = "";
for (int i = 0; i < 5; i++)
{
int rNumber = r.Next(0, 10);
str += rNumber;
}
//創建一個圖片對象
Bitmap bmp=new Bitmap(120,25);
//創建GDI對象
Graphics g = Graphics.FromImage(bmp);
// MessageBox.Show(str);
string[] fonts = { "黑體", "楷體", "微軟雅黑", "宋體", "隸書" };
Color[] colors = { Color.Red, Color.Yellow, Color.Blue, Color.Black, Color.Green };
for (int i = 0; i < 5; i++)
{
Point p=new Point(i*20,0);//0,0 20 0
g.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 5)], 20, FontStyle.Bold),new SolidBrush(colors[r.Next(0,5)]), p);
}
//畫線
for (int i = 0; i < 25; i++)
{
Point p1=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
Point p2=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
g.DrawLine(new Pen(Color.Green), p1, p2);
}
//畫像素顆粒
for (int i = 0; i < 100; i++)
{
Point p=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
bmp.SetPixel(p.X, p.Y, Color.Black);
}
//把畫好的圖片放到PictureBox上
pictureBox1.Image = bmp;
}