PrintWindow 函数在 notepad.exe 中出错

PrintWindow function makes mistake in notepad.exe

Win32API 中的 PrintWindow 函数可以捕获程序的图像。通过下面的代码我们可以在剪贴板中获取截图的副本。

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

当我使用代码截取屏幕截图时,它可以工作,但 returns 我的剪贴板中有一张错误的图片。像这样: My screenshot of notepad.exe

这似乎是记事本程序的一部分。但是为什么它只是程序的一部分。我尝试了其他程序,它们运行良好。记事本或win32api有没有bug?

你只得到客户区。此代码获取整个 window:

HWND hwnd = FindWindow(programName, nullptr);
if (hwnd == nullptr)
    return -1;

WINDOWINFO wi;
wi.cbSize = sizeof(WINDOWINFO);
GetWindowInfo(hwnd, &wi);

const LONG w = wi.rcWindow.right - wi.rcWindow.left;
const LONG h = wi.rcWindow.bottom - wi.rcWindow.top;

HDC hdcScreen = GetDC(nullptr);
HDC hdc = CreateCompatibleDC(hdcScreen);
HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, w, h);
SelectObject(hdc, hbmp);

PrintWindow(hwnd, hdc, 0); // or use PW_RENDERFULLCONTENT
BitBlt(hdc, 0, 0, w, h, hdc, 0, 0, SRCCOPY);

OpenClipboard(nullptr);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hbmp);
CloseClipboard();

DeleteDC(hdc);
DeleteObject(hbmp);

ReleaseDC(nullptr, hdcScreen);
return 0;