
.NET 2.0+Capturing the Screen Contents in .NET 2.0
When supporting installed software, descriptions of problems can be enhanced greatly by viewing the contents of the user's screen. In this article we will explore how to perform a screen grab and display the captured image in a Windows Forms application.
Creating the Application
It was not possible to capture the contents of the desktop using the early versions of the .NET framework without resorting to Windows API calls. The .NET framework 2.0 introduced several new and modified classes within the System.Drawing and System.Drawing.Imaging namespaces that make the job much simpler. Instead of using API calls, the Graphics Device Interface 'plus' (GDI+) system that was introduced in Windows XP, and is provided in later operating systems, is utilised.
To demonstrate, we will create a simple Windows Forms program that copies the contents of the screen onto the background of its main form on loading. The image will be the same as that copied to the clipboard when the Print Screen key is pressed. To begin, create a new Windows Forms application. The entire code for this sample will be held in the form's Load event so add this event using the development environment of your choice. The generated code should be similar to the following:
private void Form1_Load(object sender, EventArgs e)
{
}
The process uses two key drawing namespaces. To reference these, ensure that the following using directives appear at the top of the code file:
using System.Drawing;
using System.Drawing.Imaging;
Creating the Bitmap
The first task for the program is to create the bitmap image that will be used to hold the captured desktop contents. This image will, at the end of the process, be displayed within the application's window as the background image. It could alternatively be saved to disk or displayed in another image control according to the program's requirements.
Bitmap Size
The bitmap image will be created with a fixed size. This size must match the screen resolution exactly or the image will be cropped or contain blank areas that are simply wasting resources. To determine the screen resolution, add the following code to the Load event:
Rectangle bounds = Screen.PrimaryScreen.Bounds;
NB: In the example we are using the PrimaryScreen property to examine the contents of the main display. If multiple monitors are in use, the AllScreens array can be used to capture the other displays.
Colour Depth
The colour depth for the screen is measured in bits per pixel. Usual values for number of bits used per pixel are 8, 16, 24 and 32. The higher the number of bits, the more colours can be represented in each screen pixel giving improvements in graphical quality at the cost of memory usage. We will identify the colour depth and use a similar value for the bitmap so that memory usage is minimised.
To determine the colour depth, add the following code:
int colourDepth = Screen.PrimaryScreen.BitsPerPixel;
10 February 2008