利用CImage进行屏幕截图

来源:互联网 发布:霍布斯鲍姆 知乎 编辑:程序博客网 时间:2024/05/22 13:08

 

// 函数说明: bFull如果是真,则截取整个屏幕否则只截取活动窗口.strPath是保存图片的路径.

// 如果函数成功,则将文件保存在指定的路径,格式为PNG

BOOL CaptureScreen(BOOL bFull, CString strPath)
{
 CImage image;
 CWnd
*  pWnd;
 CRect  rect;
 BOOL   bStat;
 
if(bFull)
  pWnd 
= CWnd::GetDesktopWindow();
 
else
  pWnd 
= CWnd::GetActiveWindow();

 ASSERT(pWnd);
 
if(pWnd == NULL)
  
return FALSE;

 CWindowDC winDC(pWnd);
 pWnd
->GetWindowRect(&rect);

 
int nBPP = winDC.GetDeviceCaps(BITSPIXEL) * winDC.GetDeviceCaps(PLANES);
 
if(nBPP < 24) nBPP = 24;

 bStat 
= image.Create(rect.Width(), rect.Height(), nBPP);
 ASSERT(bStat);
 
if(!bStat)
  
return FALSE;

 CImageDC imageDC(image);

 ::BitBlt(imageDC, 
00, rect.Width(), rect.Height(), winDC, 00, SRCCOPY);
 
 CString strFull 
= MakeFilename(strPath);
 HRESULT hr 
= image.Save(strFull);
 
if(FAILED(hr))
 
{
  TRACE(
"Couldn't Save File: %s, %x ", (LPCTSTR)strFull, hr);
  
return FALSE;
 }

 
return TRUE;
}
 

 

// 函数说明:结合路径,自动产生一个文件名

CString MakeFilename(CString
& strPath)
{
 CString strRet(strPath);
 
static UINT i=0;
 
if(strRet.Right(1!= "/")
  strRet 
+= "/";

 strRet.AppendFormat(
"%03.3d.png", i++);
 
return strRet;
}


 

// 引用方法:

CaptureScreen(TRUE, 
"c:/");