简体   繁体   English

屏幕截图仅返回黑色图像

[英]Screen capture only returns a black image

I'm trying to take a screen capture of the main dialog in my MFC application and save it as an image file. 我正在尝试在MFC应用程序中截取主对话框的屏幕截图,并将其另存为图像文件。 I tried about every example I could find online and always end up with the same result: the image file has the correct dimensions (I tried this with dialogs other than the main one just to be sure), but it is all black. 我尝试了每一个可以在网上找到的示例,但最终总是得到相同的结果:图像文件具有正确的尺寸(我确定使用主对话框以外的其他对话框进行了尝试),但是它全都是黑色的。 My most recent solution is using the CBitmap class to transfer the main dialog handle to a CImage. 我最近的解决方案是使用CBitmap类将主对话框句柄转移到CImage。 Here is my code: 这是我的代码:

CWnd* mainWindow;
CDC* mainWindowDC;
CBitmap bitmapToSave;
CImage imageToSave;
CRect windowRect;

//Get main window context and create bitmap from it
mainWindow = AfxGetMainWnd();
mainWindowDC = mainWindow->GetWindowDC();
mainWindow->GetWindowRect(&windowRect);
bitmapToSave.CreateCompatibleBitmap(mainWindowDC, windowRect.Width(), windowRect.Height());
imageToSave.Attach(bitmapToSave);
imageToSave.Save("C:\\Capture\\image.bmp", Gdiplus::ImageFormatBMP);

Here is the way to do it: 这是这样做的方法:

HRESULT CaptureScreen(const CString& sImageFilePath)
{
   CWnd* pMainWnd = AfxGetMainWnd();
   CRect rc;
   pMainWnd->GetWindowRect(rc);
   CImage img;
   img.Create(rc.Width(), rc.Height(), 24);
   CDC memdc;
   CDC* pDC = pMainWnd->GetWindowDC();
   memdc.CreateCompatibleDC(pDC);
   CBitmap* pOldBitmap = memdc.SelectObject(CBitmap::FromHandle((HBITMAP)img));
   memdc.BitBlt(0, 0, rc.Width(), rc.Height(), pDC, 0, 0, SRCCOPY);
   memdc.SelectObject(pOldBitmap);
   return img.Save(sImageFilePath, Gdiplus::ImageFormatPNG);
}

Please also take a look at this nice implementation: http://www.codeguru.com/cpp/article.php/c18347/C-Programming-Easy-Screen-Capture-Using-MFCATL.htm 也请看一下这个不错的实现: http : //www.codeguru.com/cpp/article.php/c18347/C-Programming-Easy-Screen-Capture-Using-MFCATL.htm

You created the bitmap, but you didn't put anything into it. 您创建了位图,但是没有放入任何东西。 You need to blit from one DC to another to make a copy of what's on the screen. 您需要从一个DC切换到另一个DC,以复制屏幕上的内容。

// ...
CMemDC dcMem;
dcMem.CreateCompatibleDC(&mainWindowDC);
CBitmap * pOld = dcMem.SelectObject(&bitmapToSave);
dcMem.BitBlt(0, 0, windowRect.Width(), windowRect.Height(), &mainWindowDC, windowRect.left, windowRect.top, SRCCOPY);
dcMem.SelectObject(pOld);
// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM