Create a Captcha with Refresh button in c#

Create a Captcha with Refresh button in c#
captcha.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="captcha.aspx.cs" Inherits="captcha" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  
<title>Captcha Image with Refresh Button</title>
<script type="text/javascript">
    function RefreshCaptcha() {
        var img = document.getElementById("imgCaptcha");
        img.src = "Handler.ashx?query=" + Math.random();
    }
</script>
</head>
<body>
<form id="form2" runat="server">
<div>
<img src="Handler.ashx" id="imgCaptcha" />
<a href="#" onclick="javascript:RefreshCaptcha();">Refresh</a>
</div>
</form>
</body>


</html>



captcha.ashx

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;

public class Handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        using (Bitmap b = new Bitmap(150, 40, PixelFormat.Format32bppArgb))
        {
            using (Graphics g = Graphics.FromImage(b))
            {
                Rectangle rect = new Rectangle(0, 0, 149, 39);
                g.FillRectangle(Brushes.White, rect);

                // Create string to draw.
                Random r = new Random();
                int startIndex = r.Next(1, 5);
                int length = r.Next(5, 10);
                String drawString = Guid.NewGuid().ToString().Replace("-", "0").Substring(startIndex, length);

                // Create font and brush.
                Font drawFont = new Font("Arial", 16, FontStyle.Italic | FontStyle.Strikeout);
                using (SolidBrush drawBrush = new SolidBrush(Color.Black))
                {
                    // Create point for upper-left corner of drawing.
                    PointF drawPoint = new PointF(15, 10);

                    // Draw string to screen.
                    g.DrawRectangle(new Pen(Color.Red, 0), rect);
                    g.DrawString(drawString, drawFont, drawBrush, drawPoint);
                }
                b.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                context.Response.ContentType = "image/jpeg";
                context.Response.End();
            }
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Download Source Code:captchasourcecode