简体   繁体   中英

Screen capture of specific window c++

I want to take a screenshot of some specific window (eg calculator).

Here is the code I have written according to this discussion:

// Get the window handle of calculator application.
HWND hWnd = ::FindWindow(0, _T("Calculator"));
RECT r;
GetWindowRect(hWnd, &r);
int x[2]; int y[2];
x[0] = r.top;  x[1] = r.bottom;
y[0] = r.left; y[1] = r.right;

HDC     hScreen = GetWindowDC(hWnd);
HDC     hDC = CreateCompatibleDC(hScreen);
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, y[1] - y[0], x[1] - x[0]);
HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
BitBlt(hDC, 0, 0, y[1] - y[0], x[1] - x[0], hScreen, y[0], x[0], SRCCOPY);

Afterwards, I save the bitmap as a .bmp image.

The result has correct size and position of the calculator window but the resulting bmp is all black.

I tried to screenshot the full desktop and then cut the calculator part and that worked. But I want to be able to make a screenshot of the window even if it is minimized or covered by another window.

Any ideas why this code is not working or is there any other way to do it?

Thanks.

A method for consideration is CreateForWindow .

Another angle, given the target window is movable, is relocating it to the top left corner of the current desktop. Perform a capture of the entire screen , and then, given you know the dimensions of the window, crop it to those.
This has a better chance of success provided security programs can be suspended or terminated, the target window isn't cloaked , or composited in the way as discussed in the above comments, or when Aero can be temporarily disabled.

The easiest way to do that is using PrintWindow .

Here's some examples :

  • If you want to draw the whole window (with the frame), just do it this way : PrintWindow(calculatorHwnd, destHwnd, 0);
  • If you only want to capture the client area of a window, here's the way to go : PrintWindow(calculatorHwnd, destHwnd, PW_CLIENTONLY);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM