简体   繁体   中英

Convert PrintWindow to BitBlt to capture screenshot of a specific window

I have a C++ program to capture the screenshot of a specific window and save it using the following code

 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);
 }

This code works for many of the windows, but for some of the windows, the output is a black image with correct width and height. On searching I found a solution to use BitBlt() . But I cannot figure out how to replace PrintWindow() with BitBlt() and output to a HBITMAP . Help Need

First, replace hdcscreen by hdcwnd , which you get with GetDC(hwnd) instead of GetDC(NULL) . It probably won't change anything, but it is more adequate, even with PrintWindow() .
Then, just replace :

PrintWindow(hwnd,hdc,NULL);

By :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM