Win32 - How to capture a screenshot without my window in it?

I was trying to create a program that captures a screenshot and displays it in the window when you click the mouse. Because my main window will cover part of the screen, I want the screenshot to be taken without the window, like my main window did not even exist.
Right now, I'm getting a DC of the screen, and then create a memory DC and bitmap, then BitBlt the screen into the memory DC and thus the bitmap. But this way, the screenshot has my window in the picture.
I tried using ShowWindow(hWnd, SW_HIDE) before CreateDC, and then ShowWindow(hWnd, SW_SHOW) right before the StrechBlt that will copy the image from the bitmap to my window. But somehow, my window was still in the picture. I searched it up online but found no desirable answers. Can anyone help me with this?

Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//hWnd is handle to main window, rcWnd is a RECT containing the dimensions of the main window's client area
ShowWindow(hWnd, SW_HIDE);
HDC hDC = GetDC(hWnd);
FillRect(hDC, &rcWnd, (HBRUSH)(COLOR_WINDOW + 1));
HDC hScreenDC = CreateDC(_T("DISPLAY"), NULL, NULL, NULL);
int nWidth = GetDeviceCaps(hScreenDC, HORZRES);
int nHeight = GetDeviceCaps(hScreenDC, VERTRES);
HDC hCompatible = CreateCompatibleDC(hScreenDC);
HBITMAP hScreenBitmap = CreateCompatibleBitmap(hScreenDC, nWidth, nHeight);
HANDLE hOld = SelectObject(hCompatible, hScreenBitmap);
BitBlt(hCompatible, 0, 0, nWidth, nHeight, hScreenDC, 0, 0, SRCCOPY);

SetStretchBltMode(hDC, HALFTONE);

SelectObject(hCompatible, hOld);
DeleteDC(hCompatible);
DeleteDC(hScreenDC);
//later...
HDC hMemDC = CreateCompatibleDC(hDC);
HANDLE hOld2 = SelectObject(hMemDC, hScreenBitmap);
ShowWindow(hWnd, SW_SHOW);
StretchBlt(hDC, 0, 0, rcWnd.right, rcWnd.bottom, hMemDC, 0, 0, nWidth, nHeight, SRCCOPY);
SelectObject(hMemDC, hOld2);
DeleteDC(hMemDC);
DeleteObject(hScreenDC);
ReleaseDC(hWnd, hScreenDC);
Last edited on
probably sleep a second before you do bitblt.. your window may not hide so quickly.
Thanks! That did the trick for me.
Topic archived. No new replies allowed.