捕获窗口内容并转换为 QImage
| 242 | |
| 243 | // 捕获窗口内容并转换为 QImage |
| 244 | QImage Utils::captureWindowToQImage(HWND hwnd, const DWORD mode) { |
| 245 | if(hwnd == nullptr || !IsWindow(hwnd)){ |
| 246 | return QImage(); |
| 247 | } |
| 248 | |
| 249 | QMutexLocker locker(&m_locker); |
| 250 | RECT rect; |
| 251 | GetWindowRect(hwnd, &rect); |
| 252 | int width = rect.right - rect.left; |
| 253 | int height = rect.bottom - rect.top; |
| 254 | |
| 255 | // 获取窗口设备上下文 |
| 256 | HDC hdcWindow = GetDC(hwnd); |
| 257 | HDC hdcMemDC = CreateCompatibleDC(hdcWindow); |
| 258 | |
| 259 | // 创建兼容位图 |
| 260 | HBITMAP hBitmap = CreateCompatibleBitmap(hdcWindow, width, height); |
| 261 | SelectObject(hdcMemDC, hBitmap); |
| 262 | |
| 263 | // 使用 PrintWindow 捕获窗口内容 |
| 264 | // 0x00000002; 捕获完整内容,包括非客户区 |
| 265 | const DWORD PW_RENDERFULLCONTENT = mode; // 0x00000003 捕获仅客户区 实测3可以实现 |
| 266 | if (!PrintWindow(hwnd, hdcMemDC, PW_RENDERFULLCONTENT)) { |
| 267 | qWarning() << "PrintWindow failed. Unable to capture content." ; |
| 268 | DeleteObject(hBitmap); |
| 269 | DeleteDC(hdcMemDC); |
| 270 | ReleaseDC(hwnd, hdcWindow); |
| 271 | return QImage(); |
| 272 | } |
| 273 | |
| 274 | // 将 HBITMAP 转换为 QImages |
| 275 | QImage image = Utils::HBitmapToQImage(hBitmap, hdcWindow); |
| 276 | if(image.isNull()){ |
| 277 | qWarning() << QString("failed to capture window image, hwnd 0x%1").arg(reinterpret_cast<quintptr>(hwnd), 0, 16); |
| 278 | return QImage(); |
| 279 | } |
| 280 | |
| 281 | RECT clientRect; |
| 282 | GetClientRect(hwnd, &clientRect); |
| 283 | int clientWidth = clientRect.right - clientRect.left; |
| 284 | int clientHeight = clientRect.bottom - clientRect.top; |
| 285 | qDebug() << QString("client width %1, height %2").arg(clientWidth).arg(clientHeight); |
| 286 | |
| 287 | // 如果捕获的图像大于客户区,则裁剪图像 |
| 288 | qDebug() << "Original image size:" << image.size(); // 打印原始尺寸 |
| 289 | if (image.width() > clientWidth || image.height() > clientHeight) { |
| 290 | image = image.copy(0, 0, clientWidth, clientHeight); // 裁剪图像,保留左上部分 |
| 291 | qDebug() << "Image cropped to client dimensions."; |
| 292 | qDebug() << "Cropped image size:" << image.size(); // 打印裁剪后的尺寸 |
| 293 | } |
| 294 | |
| 295 | // 释放资源 |
| 296 | DeleteObject(hBitmap); |
| 297 | DeleteDC(hdcMemDC); |
| 298 | ReleaseDC(hwnd, hdcWindow); |
| 299 | |
| 300 | // 判断 QImage 类型并处理 |
| 301 | if (image.format() == QImage::Format_RGB888) { |