c++ - PrintWindow函数在notepad.exe中出错

标签 c++ windows winapi notepad

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

当我使用代码捕获屏幕截图时,它可以工作,但是将错误的图片返回到剪贴板中。像这样:
My screenshot of notepad.exe

好像是记事本程序的一部分。但是为什么它只是程序的一部分。我尝试了其他程序,它们运行良好。记事本或win32api中是否存在任何错误?

最佳答案

您只能获得客户区。此代码获取整个窗口:

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;

关于c++ - PrintWindow函数在notepad.exe中出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60263794/

相关文章:

.net - 使用 SetDefaultDllDirectories 中断字体处理

c++ - 将字符串元素转换为整数 (C++11)

c++ - 为什么我不能拥有带有此签名的 Q_PROPERTY?

c++ - Windows sleep 不一致?

windows - 如何在 cygwin 中安装 libtoolize?

c++ - 内存删除的运行时检测

c++ - 不用安装Visual Studio 2010就可以使用vc100平台工具集?

c++ - 在使用Builder Pattern的构造函数中将指针类型的成员数据初始化为NULL

c++ - 如何编写构造函数

python - 在 Python 中窗口为 "out of focus"时读取 HID 输入