c++ - 在 MFC (C++) 中捕获并保存窗口的屏幕截图
问题描述
我想在 MFC 中捕获窗口的屏幕截图并将其保存为图像文件。按照这些例子,我得到了如下的东西
OnSave()
{
CRect rect;
GetWindowRect(&rect);
CImage* img = new CImage();
img->Create(rect.Width(), rect.Height(), 32);
HDC device_context_handle = img->GetDC();
HWND hwnd = this->GetSafeHwnd();
bool IsPrint =::PrintWindow(hwnd, device_context_handle, PW_CLIENTONLY);
HRESULT res = img->Save(L"image12.bmp", Gdiplus::ImageFormatBMP);
img->ReleaseDC();
delete img;
}
这样做,我得到了正确尺寸的文件,但它总是黑色的。我检查了结果保存(res)也始终为0。我尝试在线检查不同的示例,但无法修复此黑色图像问题。有没有建议修改这个或以不同的方式做这个?
解决方案
像下面这样的事情应该这样做
int x1, y1, x2, y2, w, h;
// get window dimensions for following vars.
// Don.t know if you want all area or just client area,
// so use GetClientRect or GetWindowRect accordingly.
// These functions sometimes are not so obvious on what they do.
x1 = /**/;
y1 = /**/;
x2 = /**/;
y2 = /**/;
// width and height
w = x2 - x1;
h = y2 - y1;
// copy window to bitmap
HDC hWindow = (HDC) window.GetDC();
HDC hDC = CreateCompatibleDC(hWindow);
HBITMAP hBitmap = CreateCompatibleBitmap(hWindow, w, h);
HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
BOOL bRet = BitBlt(hDC, 0, 0, w, h, hWindow, x1, y1, SRCCOPY);
CImage image;
image.Attach(hBitmap);
image.Save(debug_dir + L"window.bmp", Gdiplus::ImageFormatBMP);
// clean-up
SelectObject(hDC, old_obj);
DeleteDC(hDC);
::ReleaseDC(NULL, hWindow);
DeleteObject(hBitmap);
推荐阅读
- postgresql - 是否可以从 SageMaker Data Wrangler 连接到 Postgres 数据库?
- python - 如何使我的 Python 程序提供的功能可用于在同一台或其他计算机上运行的以其他语言编写的程序?
- get - 使用 fetch GET 请求发送参数
- grep - grep文件如果匹配删除它并以相同的名称保存
- c# - EF-Core 无法识别迁移中的表名更改
- c# - 读取 XML 文件以创建 3D 模型
- python - 无法导入包python
- javascript - 纯 JavaScript 幻灯片播放/暂停与空格键
- python - 长日期转换为季度(用句点大写)
- android - setonclicklistner 在 kotlin 中不起作用