Screen capture of specific window c++

人盡茶涼 提交于 2021-01-01 08:57:53

问题


I want to take a screenshot of some specific window (e.g 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.


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/43925820/screen-capture-of-specific-window-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!