可以使Qt下的
grabWindow(WId window, int x = 0, int y = 0, int width = -1, int height = -1)
创建并返回一个QPixmap,通过抓取给定窗口的内容(x、y、width、height)。
参数(x、y)指定窗口中的偏移量,而(width、height)指定要复制的区域。如果宽度为负,则函数将所有内容复制到窗口的右边界。如果高度为负,则该函数将所有内容复制到窗口的底部。
可以使用QWidget::winId()函数检索窗口系统标识符(WId)。使用窗口标识符而不是QWidget的基本原理是,允许抓取不属于应用程序、窗口系统框架的窗口,等等。
主要实现代码:
QPixmap m_pixmap = QPixmap::grabWindow(QApplication::desktop()->winId());
m_pixmap ->save("test.jpg");
但是这种方法有一个缺点,就是无法抓取鼠标;这是QT grabWindow实现里面就不抓mouse cursor的
具体实现如下
QPixmap QPixmap::grabWindow(WId winId, int x, int y, int w, int h )
{
RECT r;
GetClientRect(winId, &r);
if (w < 0) w = r.right - r.left;
if (h < 0) h = r.bottom - r.top;
#ifdef Q_WS_WINCE_WM
if (qt_wince_is_pocket_pc()) {
QWidget *widget = QWidget::find(winId);
if (qobject_cast<QDesktopWidget *>(widget)) {
RECT rect = {0,0,0,0};
AdjustWindowRectEx(&rect, WS_BORDER | WS_CAPTION, FALSE, 0);
int magicNumber = qt_wince_is_high_dpi() ? 4 : 2;
y += rect.top - magicNumber;
}
}
#endif
// Create and setup bitmap
HDC display_dc = GetDC(0);
HDC bitmap_dc = CreateCompatibleDC(display_dc);
HBITMAP bitmap = CreateCompatibleBitmap(display_dc, w, h);
HGDIOBJ null_bitmap = SelectObject(bitmap_dc, bitmap);
// copy data
HDC window_dc = GetDC(winId);
BitBlt(bitmap_dc, 0, 0, w, h, window_dc, x, y, SRCCOPY
#ifndef Q_WS_WINCE
| CAPTUREBLT
#endif
);
// clean up all but bitmap
ReleaseDC(winId, window_dc);
SelectObject(bitmap_dc, null_bitmap);
DeleteDC(bitmap_dc);
QPixmap pixmap = QPixmap::fromWinHBITMAP(bitmap);
DeleteObject(bitmap);
ReleaseDC(0, display_dc);
return pixmap;
}
所以还是换别的思路吧;那就自己将方法实现。不多说直接上代码
QPixmap MainWindow::grabWindow(HWND winId, int x, int y, int w, int h)
{
RECT r;
GetClientRect(winId, &r);
if (w < 0) w = r.right - r.left;
if (h < 0) h = r.bottom - r.top;
HDC display_dc = GetDC(winId);
HDC bitmap_dc = CreateCompatibleDC(display_dc);
HBITMAP bitmap = CreateCompatibleBitmap(display_dc, w, h);
HGDIOBJ null_bitmap = SelectObject(bitmap_dc, bitmap);
BitBlt(bitmap_dc, 0, 0, w, h, display_dc, x, y, SRCCOPY | CAPTUREBLT);
CURSORINFO ci;
ci.cbSize = sizeof(CURSORINFO);
GetCursorInfo(&ci);
if((ci.ptScreenPos.x > x) && (ci.ptScreenPos.y > y) && (ci.ptScreenPos.x < (x+w)) && (ci.ptScreenPos.y < (y+h)))
DrawIcon(bitmap_dc, ci.ptScreenPos.x-x, ci.ptScreenPos.y-y, ci.hCursor);
// clean up all but bitmap
ReleaseDC(winId, display_dc);
SelectObject(bitmap_dc, null_bitmap);
DeleteDC(bitmap_dc);
QPixmap pixmap = QtWin::fromHBITMAP(bitmap);
DeleteObject(bitmap);
return pixmap;
}