Subscribe

RSS Feed (xml)

Perform a Screen Capture

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 that displays the captured image in a picture box.

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;
    }
}

Technorati :

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail