With Silverlight it is possible to create Bitmap images which gives us the option to generate Captcha images to validate input from a human being. Generating Captcha is a two step process

  1. Generate Captcha code
  2. Create Image to display the code

We will see a very basic example of Captcha code generation and validation here. The source code can be downloaded from here

In order to generate Captcha code we will randomly select chars from an array which will contain all allowed characters to be shown in the Captcha code.

char[] charArray =

char[] captcha = new char[6];
for (int i = 0; i < captcha.Length; i++)
captcha[i] = charArray[random.Next(charArray.Length)];
CaptchaCode = new string(captcha);

Next step would be to generate a Bitmap image to be shown to the users

private WriteableBitmap GenerateBitmap()
// Capcha code textblock to render to a bitmap
TextBlock t = new TextBlock();
t.Height = 25;
t.Width = 60;
t.Text = this.CaptchaCode;
t.FontSize = 12;
t.Padding = new Thickness(5, 5, 5, 5);
t.Foreground = new SolidColorBrush(Colors.White);

// Create bitmap
WriteableBitmap bitmap = new WriteableBitmap(60, 25);
SkewTransform tr = new SkewTransform() { AngleX = -5, AngleY = -10 };
bitmap.Render(t, tr);

// invalidate the bitmap to render it
return bitmap;

Once we have the Bitmap image it can be assigned to an Image control in your XAML as shown below

<Border Height=”30″ Grid.Column=”0″ Grid.Row=”1″ Background=”#FFAD4343″ Opacity=”1.0″ VerticalAlignment=”Center” HorizontalAlignment=”Center”>
<Image VerticalAlignment=”Bottom” x:Name=”ImgCapcha” Height=”25″></Image>

Users will be required to enter the code in a text box and the code will be validated using a button click (SEE PICTURE).

<TextBox Grid.Row=”3″ Width=”100″ Height=”25″ x:Name=”EnteredCode”></TextBox>
<Button x:Name=”BtnSubmit” Grid.Row=”4″ Width=”40″ Height=”25″ Content=”OK” Click=”BtnSubmit_Click”></Button>

In the Silverlight control Captcha code can be initialized and validated as shown below

public partial class MainPage : UserControl
CaptchaCodeHandler c;

public MainPage()

private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)

private void LoadCaptchaCode()
c = new CaptchaCodeHandler();
ImgCapcha.Source = c.CaptchaImage;

private void BtnSubmit_Click(object sender, RoutedEventArgs e)
if (c.ValidateCaptchaCode(EnteredCode.Text))
System.Windows.Browser.HtmlPage.Window.Alert(“Correct code entered”);
System.Windows.Browser.HtmlPage.Window.Alert(“Wrong code entered. Enter next code”);

Simple Captcha code implemenation for Silverlight

Leave a Reply

Your email address will not be published. Required fields are marked *