Home / Code Snippets / Blog article: Programmatically Take Screenshot Using C#

| RSS

Programmatically Take Screenshot Using C#

February 26th, 2009 | 4 Comments | Posted in Code Snippets

To do this you will need to add references to System.Drawing and System.Windows.Forms. Make sure that you have following using statements:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

 

In your method add this code. It will take a screenshot of your primary screen and save it to a file.

Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                  Screen.PrimaryScreen.Bounds.Height);

Graphics graphics = Graphics.FromImage(bitmap as Image);

graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

bitmap.Save(@"c:\temp\screenshot.bmp", ImageFormat.Bmp);






Leave a Reply 4839 views, 8 so far today |
Tags: ,
Follow Discussion

4 Responses to “Programmatically Take Screenshot Using C#”

  1. TJ Says:

    Hello!
    Is it possible to get a screenshot of a window that is not on the top, i.e. if it is partially hided by another window, without bringing it to the top?
    Thanx
    TJ

  2. Deepak Says:

    Hi TJ,

    I have never tried this. But I believe it should be possible maybe using Win32 APIs.

  3. Michael L Says:

    Yes, you can use the win32 api to get a screen shot of any window.
    If it’s minimized or hidden, the graphics device will likely be blanked out as the apps don’t generally paint then.

    I posted a class to do it here:
    http://www.machinegods.com/node/18

    Here’s the method of interest without all the pinvoke declarations:

    public static Bitmap Get(IntPtr hWnd)
    {
    WINDOWINFO winInfo = new WINDOWINFO();
    bool ret = GetWindowInfo(hWnd, ref winInfo);
    if (!ret)
    {
    return null;
    }

    int height = winInfo.rcWindow.Height;
    int width = winInfo.rcWindow.Width;
    if (height == 0 || width == 0) return null;

    Graphics frmGraphics = Graphics.FromHwnd(hWnd);
    IntPtr hDC = GetWindowDC(hWnd); //gets the entire window
    //IntPtr hDC = frmGraphics.GetHdc(); — gets the client area, no menu bars, etc..

    System.Drawing.Bitmap tmpBitmap = new System.Drawing.Bitmap(width, height, frmGraphics);
    Graphics bmGraphics = Graphics.FromImage(tmpBitmap);
    IntPtr bmHdc = bmGraphics.GetHdc();

    BitBlt(bmHdc, 0, 0,width, height, hDC, 0, 0, TernaryRasterOperations.SRCCOPY);

    bmGraphics.ReleaseHdc(bmHdc);
    ReleaseDC(hWnd, hDC);

    return tmpBitmap;
    }

  4. Deepak Says:

    Thank you Michael for the code sample.

Leave a Reply