创建并获取窗口句柄
view->show();
view->createWinId();
auto wid = view->winId();
获取图片
QTimer::singleShot(3000, [wid]() {
auto&& image = GetGDIBitmap((HWND)wid);
image.save("test.png");
});
主要实现
#pragma once
#include <QImage>
#include <wtypes.h>
QImage BitmapToQImage(HBITMAP&);
QImage GetGDIBitmap(HWND);
inline QImage GetGDIBitmap(HWND hd)
{
RECT rect;
GetWindowRect(hd, &rect);
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
HDC hdc = GetDC(hd);
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hBitmap = CreateCompatibleBitmap(hdc, width, height);
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hdcMem, hBitmap);
BitBlt(hdcMem, 0, 0, width, height, hdc, 0, 0, SRCCOPY);
SelectObject(hdcMem, hOldBitmap);
DeleteDC(hdcMem);
ReleaseDC(hd, hdc);
QImage image = BitmapToQImage(hBitmap);
DeleteObject(hBitmap);
return image;
}
inline QImage BitmapToQImage(HBITMAP& hBitmap)
{
BITMAP bitmap;
GetObject(hBitmap, sizeof(BITMAP), &bitmap);
QImage img(bitmap.bmWidth, bitmap.bmHeight, QImage::Format_ARGB32);
HDC hdc = CreateCompatibleDC(NULL);
HBITMAP hBitOld = (HBITMAP)SelectObject(hdc, hBitmap);
for (int i = 0; i < bitmap.bmHeight; i++) {
QRgb* line = (QRgb*)img.scanLine(i);
for (int j = 0; j < bitmap.bmWidth; j++) {
COLORREF clr = GetPixel(hdc, j, i);
line[j] = qRgba(GetRValue(clr), GetGValue(clr), GetBValue(clr), 255);
}
}
SelectObject(hdc, hBitOld);
DeleteDC(hdc);
return img;
}