Windows Forms: Captcha generator in C#

This post shows you how to create captcha in c# windows forms application. To create a captcha generator in c# programming is easy, you can easily follow the steps below.

Drag the PictureBox, Label, TextBox and Button from the visual studio toolbox to your winform, then design a simple UI that allows you to enter the text, then generator captcha image in c# as shown below.

captcha generator c#

To generate the captcha image, you can create the CaptchaToImage method as the following c# code.

private Bitmap CaptchaToImage(string text, int width, int height)
{
    Bitmap bmp = new Bitmap(width, height);
    Graphics g = Graphics.FromImage(bmp);
    SolidBrush sb = new SolidBrush(Color.White);
    g.FillRectangle(sb, 0, 0, bmp.Width, bmp.Height);
    Font font = new Font("Tahoma", 45);
    sb = new SolidBrush(Color.Black);
    g.DrawString(text, font, sb, bmp.Width / 2 - (text.Length / 2) * font.Size, (bmp.Height / 2) - font.Size);
    int count = 0;
    Random rand = new Random();
    while (count < 1000)
    {
        sb = new SolidBrush(Color.YellowGreen);
        g.FillEllipse(sb, rand.Next(0, bmp.Width), rand.Next(0, bmp.Height), 4, 2);
        count++;
    }
    count = 0;
    while (count < 25)
    {
        g.DrawLine(new Pen(Color.Bisque), rand.Next(0, bmp.Width), rand.Next(0, bmp.Height), rand.Next(0, bmp.Width), rand.Next(0, bmp.Height));
        count++;
    }
    return bmp;
}

Add code to handle the Generate button click event allows you to generate the captcha image in c# as shown below.

private void btnGenerate_Click(object sender, EventArgs e)
{
    picCaptcha.Image = CaptchaToImage(txtCaptcha.Text, picCaptcha.Width, picCaptcha.Height);
}

Press F5 to run the application, then enter the text and click the generate button to generator the captcha image.

You can also create the random method allows you to random a number from 10000 to 99999, then convert the number to string.

public string RandomString()
{
    Random rnd = new Random();
    int number = rnd.Next(10000, 99999);
    return MD5(number.ToString()).ToUpperInvariant().Substring(0, 6);
}

Next, You can use the MD5 algorithm to hash the string.

public string MD5(string input)
{
    using (System.Security.Cryptography.MD5CryptoServiceProvider cryptoServiceProvider = new System.Security.Cryptography.MD5CryptoServiceProvider())
    {
        byte[] hashedBytes = cryptoServiceProvider.ComputeHash(UnicodeEncoding.Unicode.GetBytes(input));
        return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
    }
}

To generate a random captcha image you should modify your c# code as shown below.

picCaptcha.Image = CaptchaToImage(RandomString(), picCaptcha.Width, picCaptcha.Height);

Related Posts