HWND hwnd ; // 获取窗口句柄 hwnd = windows.at(ui->spinBox->value()); // 获取窗口的设备上下文 HDC hdcWindow = GetDC(hwnd); // 获取窗口的客户区大小 RECT rect; GetClientRect(hwnd, &rect); int width = rect.right - rect.left; int height = rect.bottom - rect.top; // 创建一个和窗口设备上下文兼容的位图 HDC hdcMemDC = CreateCompatibleDC(hdcWindow); HBITMAP hbmScreen = CreateCompatibleBitmap(hdcWindow, width, height); HBITMAP hbmOldBitmap = (HBITMAP)SelectObject(hdcMemDC, hbmScreen); // 将窗口的内容复制到位图中 BitBlt(hdcMemDC, 0, 0, width, height, hdcWindow, 0, 0, SRCCOPY); // 将位图转换成 QPixmap BITMAPINFO info; GetObject(hbmOldBitmap, sizeof(BITMAPINFO), &info); QImage image = QImage(width, height, QImage::Format_ARGB32); QPixmap pixmap = QPixmap::fromImage(image); // 保存截图 pixmap.save("screenshot.png"); // 清理资源 SelectObject(hdcMemDC, hbmOldBitmap); DeleteObject(hbmScreen); DeleteDC(hdcMemDC); ReleaseDC(hwnd, hdcWindow);图片没内容
时间: 2024-02-14 09:12:03 浏览: 428
根据你提供的代码,可能是因为在将窗口截图复制到位图中的过程中出现了问题。具体来说,以下代码可能存在问题:
```cpp
// 将窗口的内容复制到位图中
BitBlt(hdcMemDC, 0, 0, width, height, hdcWindow, 0, 0, SRCCOPY);
```
请确保 `hwnd` 句柄指向的窗口是可见的,并且在调用 `BitBlt()` 函数之前,窗口已经完成了绘制。你可以在 `BitBlt()` 函数调用之前加入 `Sleep()` 函数等待一段时间,或者在窗口的消息循环中加入 `UpdateWindow()` 函数强制重绘窗口。
此外,还需要检查位图句柄是否正确创建。以下代码可能存在问题:
```cpp
HBITMAP hbmScreen = CreateCompatibleBitmap(hdcWindow, width, height);
HBITMAP hbmOldBitmap = (HBITMAP)SelectObject(hdcMemDC, hbmScreen);
```
请确保 `CreateCompatibleBitmap()` 函数返回的位图句柄 `hbmScreen` 不为 NULL,并且在调用 `SelectObject()` 函数之前,`hdcMemDC` 句柄已经创建成功。
最后,需要注意的是,以下代码存在一个问题:
```cpp
QImage image = QImage(width, height, QImage::Format_ARGB32);
QPixmap pixmap = QPixmap::fromImage(image);
```
在将位图转换为 QPixmap 对象时,应该使用 `QPixmap::fromWinHBITMAP()` 函数,而不是 `QPixmap::fromImage()` 函数。具体来说,应该将上述代码改为:
```cpp
HBITMAP hbmPixmap = (HBITMAP)pixmap.toWinHBITMAP();
QPixmap result = QPixmap::fromWinHBITMAP(hbmPixmap);
```
这样,就可以将位图成功转换为 QPixmap 对象了。
阅读全文
相关推荐



















