在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);

相关内容

  • 没有找到相关文章

最新更新