Convert PrintWindow to BitBlt to capture a screenshot of a specific window
I have a C ++ program to capture a 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 windows, but for some windows it is a black image with the correct width and height. While searching, I found a solution to use BitBlt()
. But I can't figure out how to replace PrintWindow()
with BitBlt()
and output to HBITMAP
. Do you need help
source to share
First replace hdcscreen
with hdcwnd
which you get with GetDC(hwnd)
instead of GetDC(NULL)
. This probably won't change anything, but more adequately, 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 );
source to share