如何在C++中获取窗口截图并生成位图对象?假设我已经拥有了窗口句柄。 我还想知道是否可能在窗口最小化时获取窗口的截图?
C++ 在这里指的是VC++,使用与Windows XP+(win32)相关的所有库。
如何在C++中获取窗口截图并生成位图对象?假设我已经拥有了窗口句柄。 我还想知道是否可能在窗口最小化时获取窗口的截图?
C++ 在这里指的是VC++,使用与Windows XP+(win32)相关的所有库。
您应该调用PrintWindow API:
void CScreenShotDlg::OnPaint()
{
// device context for painting
CPaintDC dc(this);
// Get the window handle of calculator application.
HWND hWnd = ::FindWindow( 0, _T( "Calculator" ));
// Take screenshot.
PrintWindow( hWnd,
dc.GetSafeHdc(),
0 );
}
请看这个问题:获取窗口截图的Windows API
如果您不使用MFC,这里是纯PrintWindow函数的签名:
BOOL PrintWindow(
HWND hwnd,
HDC hdcBlt,
UINT nFlags
);
更多详情请参阅MSDN:http://msdn.microsoft.com/en-us/library/dd162869(v=vs.85).aspx
如Matteo所说,如何将其保存为位图取决于您实际使用的框架...
编辑:
这里是原始C++的完整示例:
#define _WIN32_WINNT 0x0501 //xp
#include <windows.h>
int main()
{
RECT rc;
HWND hwnd = FindWindow(TEXT("Notepad"), NULL); //the window can't be min
if (hwnd == NULL)
{
cout << "it can't find any 'note' window" << endl;
return 0;
}
GetClientRect(hwnd, &rc);
//create
HDC hdcScreen = GetDC(NULL);
HDC hdc = CreateCompatibleDC(hdcScreen);
HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen,
rc.right - rc.left, rc.bottom - rc.top);
SelectObject(hdc, hbmp);
//Print to memory hdc
PrintWindow(hwnd, hdc, PW_CLIENTONLY);
//copy to clipboard
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hbmp);
CloseClipboard();
//release
DeleteDC(hdc);
DeleteObject(hbmp);
ReleaseDC(NULL, hdcScreen);
cout << "success copy to clipboard, please paste it to the 'mspaint'" << endl;
return 0;
}
看起来PrintWindow正在使用前缓冲区。我试图截取IE的屏幕截图。打开一个新链接,然后尝试获取图片。它将显示前一个链接的图片。
HBITMAP
? - Matteo Italia