C# Code Snippets

Taking Screenshots with C#

Visual C# Kicks

The code uses GDI in C#.NET to draw the primary screen onto a bitmap.

Platform: .NET Framework 2.0

public class API
    [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
    public static extern IntPtr GetDC(IntPtr hWnd);

    [DllImport("user32.dll", ExactSpelling = true)]
    public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);

    [DllImport("gdi32.dll", ExactSpelling = true)]
    public static extern IntPtr BitBlt(IntPtr hDestDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);

    [DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
    public static extern IntPtr GetDesktopWindow();

internal class ScreenShot
    public static Bitmap Take()
        int screenWidth = Screen.PrimaryScreen.Bounds.Width;
        int screenHeight = Screen.PrimaryScreen.Bounds.Height;

        Bitmap screenBmp = new Bitmap(screenWidth, screenHeight);
        Graphics g = Graphics.FromImage(screenBmp);

        IntPtr dc1 = API.GetDC(API.GetDesktopWindow());
        IntPtr dc2 = g.GetHdc();

        //Main drawing, copies the screen to the bitmap
        //last number is the copy constant
        API.BitBlt(dc2, 0, 0, screenWidth, screenHeight, dc1, 0, 0, 13369376);

        //Clean up
        API.ReleaseDC(API.GetDesktopWindow(), dc1);

        return screenBmp;

Back to C# Code Snippet List