问题描述
我想在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,h);
HGDIOBJ old_obj = SelectObject(hDC,hBitmap);
BOOL bRet = BitBlt(hDC,h,hWindow,x1,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);