简体   繁体   English

特定窗口 C++ 的屏幕截图

[英]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.之后,我将位图保存为 .bmp 图像。

The result has correct size and position of the calculator window but the resulting bmp is all black.结果具有计算器窗口的正确大小和位置,但生成的 bmp 全黑。

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 .一种可供考虑的方法是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.如果安全程序可以被暂停或终止,目标窗口没有隐藏,或者以上述评论中讨论的方式合成,或者当 Aero 可以暂时禁用时,这有更好的成功机会。

The easiest way to do that is using PrintWindow .最简单的方法是使用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);如果你想绘制整个窗口(带框架),只需这样做: 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);如果您只想捕获窗口的客户区,可以使用以下方法: PrintWindow(calculatorHwnd, destHwnd, PW_CLIENTONLY);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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