PrintWindow function in Win32API could capture the image of a program. By the following code we can get the copy of the screenshot in clipboard.
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <iostream>
using namespace std;
WCHAR programName[] = L"Notepad";
int main()
{
HWND hwnd = FindWindow(programName, NULL);
if (hwnd == NULL)
{
cerr << "Cannot find window" << endl;
return -1;
}
WINDOWINFO wi;
wi.cbSize = sizeof(WINDOWINFO);
GetWindowInfo(hwnd, &wi);
RECT rc = {
wi.rcClient.left - wi.rcWindow.left,
wi.rcClient.top - wi.rcWindow.top,
wi.rcClient.right - wi.rcWindow.left,
wi.rcClient.bottom - wi.rcWindow.top
};
HDC hdcScreen = GetDC(NULL);
HDC hdc = CreateCompatibleDC(hdcScreen);
HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen,
wi.rcWindow.right - wi.rcWindow.left,
wi.rcWindow.bottom - wi.rcWindow.top);
SelectObject(hdc, hbmp);
HBITMAP hbmp2 = CreateCompatibleBitmap(hdcScreen,
wi.rcClient.right - wi.rcClient.left,
wi.rcClient.bottom - wi.rcClient.top);
HDC hdc2 = CreateCompatibleDC(hdcScreen);
SelectObject(hdc2, hbmp2);
PrintWindow(hwnd, hdc, 0);
BitBlt(hdc2,
0, 0, rc.right - rc.left, rc.bottom - rc.top,
hdc,
rc.left, rc.top,
SRCCOPY);
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hbmp2);
CloseClipboard();
DeleteDC(hdc);
DeleteObject(hbmp);
DeleteDC(hdc2);
DeleteObject(hbmp2);
ReleaseDC(NULL, hdcScreen);
cout << "Success" << endl;
return 0;
}
When I use the code to capture a screenshot, it works but returns a wrong picture into my clipboard. Like this: My screenshot of notepad.exe
It seems like part of the notepad program. But why it is just the part of the program. I tried other programs and they works well. Is there any bugs in notepad or win32api?