How can I take a screenshot in a windows application?

0 votes
asked Jul 20, 2010 by user63898

How can I take a screenshot of the current screen using Win32?

4 Answers

0 votes
answered Jul 20, 2010 by bob-moore

There is a MSDN sample, Capturing an Image, for capturing an arbitrary HWND to a DC (you could try passing the output from GetDesktopWindow to this). But how well this will work under the new desktop compositor on Vista/Windows 7, I don't know.

0 votes
answered Jul 20, 2010 by jerry-coffin
  1. Use GetDC(NULL); to get a DC for the entire screen.
  2. Use CreateCompatibleDC to get a compatible DC.
  3. Use CreateCompatibleBitmap to create a bitmap to hold the result.
  4. Use SelectObject to select the bitmap into the compatible DC.
  5. Use BitBlt to copy from the screen DC to the compatible DC.
  6. Deselect the bitmap from the compatible DC.

When you create the compatible bitmap, you want it compatible with the screen DC, not the compatible DC.

0 votes
answered Jul 20, 2010 by woody
// get the device context of the screen
HDC hScreenDC = CreateDC("DISPLAY", NULL, NULL, NULL);     
// and a device context to put it in
HDC hMemoryDC = CreateCompatibleDC(hScreenDC);

int width = GetDeviceCaps(hScreenDC, HORZRES);
int height = GetDeviceCaps(hScreenDC, VERTRES);

// maybe worth checking these are positive values
HBITMAP hBitmap = CreateCompatibleBitmap(hScreenDC, width, height);

// get a new bitmap
HBITMAP hOldBitmap = (HBITMAP) SelectObject(hMemoryDC, hBitmap);

BitBlt(hMemoryDC, 0, 0, width, height, hScreenDC, 0, 0, SRCCOPY);
hBitmap = (HBITMAP) SelectObject(hMemoryDC, hOldBitmap);

// clean up

// now your image is held in hBitmap. You can save it or do whatever with it
0 votes
answered Jul 31, 2015 by pcunite
void GetScreenShot(void)
    int x1, y1, x2, y2, w, h;

    // get screen dimensions
    x1  = GetSystemMetrics(SM_XVIRTUALSCREEN);
    y1  = GetSystemMetrics(SM_YVIRTUALSCREEN);
    x2  = GetSystemMetrics(SM_CXVIRTUALSCREEN);
    y2  = GetSystemMetrics(SM_CYVIRTUALSCREEN);
    w   = x2 - x1;
    h   = y2 - y1;

    // copy screen to bitmap
    HDC     hScreen = GetDC(NULL);
    HDC     hDC     = CreateCompatibleDC(hScreen);
    HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h);
    HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
    BOOL    bRet    = BitBlt(hDC, 0, 0, w, h, hScreen, x1, y1, SRCCOPY);

    // save bitmap to clipboard
    SetClipboardData(CF_BITMAP, hBitmap);

    // clean up
    SelectObject(hDC, old_obj);
    ReleaseDC(NULL, hScreen);
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter