Capture the screenshot of Silverlight application in Silverlight 4


This article shows how we can easily grab the snapshot of a Silverlight application.

Introduction

It is easy to grab the snapshot of a Silverlight application at any stage and can be easily stored into database.

Sometimes it will be very useful to take the screen shot of any part of a silverlight application, mainly when error occurs in the application, to help debugging. Very useful to capture snapshot of the application state when user submits feedback on the application.

Capturing the snapshot of Silverlight application made easy with the availability of WriteableBitmap class with System.Windows.Media.Imaging namespace.

 WriteableBitmap class has the following constructors which allow us to pass the LayoutRoot (visual root of the application) or any particular UIElement in visual tree and take the screenshot of it.

It internally draws whatever the XAML looks like in the UI into a bitmap image. You can then display a thumbnail or save the bitmap to database or open a dialog box for user to save onto his machine.

Screenshot for the example:

Take screenshot of silverlight application

XAML code for the example written in MainPage.xaml:

<grid x:name="LayoutRoot" background="White">
    <grid.rowdefinitions>
        <rowdefinition>
        <rowdefinition>
        <rowdefinition>
    </rowdefinition></rowdefinition></rowdefinition></grid.rowdefinitions>
    <img x:name="img" grid.row="0" source="images/Apple.jpg" width="350" height="200">
    <stackpanel orientation="Horizontal" grid.row="1" horizontalalignment="Center">
        </stackpanel></grid>
C# code for the example written in MainPage.xaml.cs:

/// <summary>
/// Handles the Click event of the btnCapture control.
/// </summary>
/// <param name="sender">The source of the event.
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"> instance containing the event data.
private void btnCapture_Click(object sender, RoutedEventArgs e)
{
    // Create Bitmap image by passing UIElement to WriteableBitmap constructor 
    WriteableBitmap bmp = new WriteableBitmap(LayoutRoot, null);
            
    // Display captured snapshot or can save to database
    Image img = new Image();
    img.Margin = new Thickness(10);
    img.Source = bmp;
    capturedImages.Children.Add(img);
}

[UPDATED] Check the continuation article - "Saving the captured Silverlight 4 screenshot to database or send it as an email attachment"


Related tags

Silverlight,Snapshot application