首先 制作一个验证码界面 .aspx
后台代码
protected void Page_Load(object sender, EventArgs e) { List<Color> clist = new List<Color>(); clist.Add(Color.Red); clist.Add(Color.Firebrick); clist.Add(Color.LawnGreen); clist.Add(Color.Goldenrod); clist.Add(Color.Cyan); clist.Add(Color.DarkSlateBlue); clist.Add(Color.Indigo); Random r = new Random(); string s = ""; string all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmeopqrstuvwxyz0123456789"; for (int i = 0; i < 4; i++) { s += all.Substring(r.Next(0, all.Length), 1); } Session["YZM"] = s; Bitmap img = new Bitmap(120, 60); Graphics g2 = Graphics.FromImage(img); Brush b2 = new SolidBrush(clist[r.Next(0, clist.Count)]); g2.FillRectangle(b2, 0, 0, 120, 60); Graphics g = Graphics.FromImage(img); Font f = new Font("微软雅黑", 30); Brush b = new SolidBrush(Color.Red); g.DrawString(s, f, b, new PointF(0, 0)); for (int i = 0; i < 8; i++) { Graphics g3 = Graphics.FromImage(img); Pen p3 = new Pen(new SolidBrush(clist[r.Next(0, clist.Count)]), r.Next(2, 5)); g3.DrawLine(p3, new Point(r.Next(0, 120), r.Next(0, 60)), new Point(r.Next(0, 120), r.Next(0, 60))); } img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png); }
要使用的界面 .aspx
使用的控件
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<img id="yzm1" src="YZM.aspx" /><br />
<asp:Button ID="Button1" runat="server" Text="验证" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
JS 代码
<script type="text/javascript">
var a = 0;
document.getElementById("yzm1").onclick = function () {
this.src = "yzm.aspx?a=" + a;
a++;
}
</script>
后台空内容对错
Button1.Click += Button1_Click;
void Button1_Click(object sender, EventArgs e)
{
Label2.Text = Session["YZM"].ToString();
if (TextBox1.Text == Session["YZM"].ToString())
Label1.Text = "正确!!!";
else
Label1.Text = "错误!!!!!!!";
}