8.6 Perform a Screen Capture


Problem

You need to take a snapshot of the current desktop.

Solution

Use the Win32 API calls GetDesktopWindow , GetDC , and ReleaseDC from the user32.dll. In addition, use GetCurrentObject from gdi32.dll.

Discussion

The .NET Framework doesn't expose any classes for capturing the full screen (often referred to as the desktop window ). However, you can access these features by using P/Invoke with the Win32 API.

The first step is to create a class that encapsulates the Win32 API functions you need to use. The following example shows a class that declares these functions and uses them in a public Capture method to return a .NET Image object with the desktop window.

 using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; public class DesktopCapture {     [DllImport("user32.dll")]     private extern static IntPtr GetDesktopWindow();     [DllImport("user32.dll")]     private extern static IntPtr GetDC(IntPtr windowHandle);     [DllImport("gdi32.dll")]     private extern static IntPtr GetCurrentObject(IntPtr hdc,       ushort objectType);     [DllImport("user32.dll")]     private extern static void ReleaseDC( IntPtr hdc );     const int OBJ_BITMAP = 7;     public static Bitmap Capture() {              // Get the device context for the desktop window.         IntPtr desktopWindow = GetDesktopWindow();         IntPtr desktopDC = GetDC( desktopWindow );         // Get a GDI handle to the image.         IntPtr desktopBitmap = GetCurrentObject(desktopDC, OBJ_BITMAP);         // Use the handle to create a .NET Image object.         Bitmap desktopImage = Image.FromHbitmap( desktopBitmap );         // Release the device context and return the image.         ReleaseDC(desktopDC);         return desktopImage;     } } 

The next step is to create a client that can use this functionality. The following code creates a form (shown in Figure 8.6) that displays the captured image in a picture box (which is inside a scrollable panel, as described in recipe 8.5).

 public class ScreenCapture : System.Windows.Forms.Form {     private System.Windows.Forms.PictureBox pictureBox1;     private System.Windows.Forms.Panel panel1;     // (Designer code omitted.)     private void cmdCapture_Click(object sender, System.EventArgs e) {              pictureBox1.Image = DesktopCapture.Capture();         pictureBox1.Size = pictureBox1.Image.Size;     } } 
click to expand
Figure 8.6: Capturing the screen contents.



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net