将 PrintWindow 转换为 BitBlt 以捕获特定 window 的屏幕截图

Convert PrintWindow to BitBlt to capture screenshot of a specific window

我有一个 C++ 程序可以捕获特定 window 的屏幕截图并使用以下代码保存它

 int main()
 {
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   RECT rc;
   HWND hwnd = FindWindow(NULL,TEXT("Window Title Here"));
   if(hwnd == NULL)
   {
      cout<<"Can't Find Window";
      return 0;
   }

    GetClientRect(hwnd,&rc);

    HDC hdcscreen = GetDC(NULL);
    HDC hdc = CreateCompatibleDC(hdcscreen);

    HBITMAP hbmp = CreateCompatibleBitmap(hdcscreen,rc.right - rc.left,rc.bottom - rc.top);

    SelectObject(hdc,hbmp);

    PrintWindow(hwnd,hdc,NULL);

    BitmapToJpg(hbmp,rc.right - rc.left,rc.bottom-rc.top); //Function to convert hbmp bitmap to jpg

    DeleteDC(hdc);
    DeleteObject(hbmp);
    ReleaseDC(NULL,hdcscreen);
 }

此代码适用于许多 windows,但对于某些 windows,输出是具有正确宽度和高度的黑色图像。在搜索时,我找到了使用 BitBlt() 的解决方案。但我不知道如何用 BitBlt() 替换 PrintWindow() 并输出到 HBITMAP。需要帮助

首先,用 hdcwnd 替换 hdcscreen,用 GetDC(hwnd) 代替 GetDC(NULL)。它可能不会改变任何东西,但它更足够了,即使 PrintWindow().
然后,只需替换 :

PrintWindow(hwnd,hdc,NULL);

作者:

BitBlt( hdc, 0, 0, rc.right - rc.left,rc.bottom-rc.top, hdcwnd, 0, 0, SRCCOPY );