思路: (1)获取当前顶层窗口(即屏幕)(GetDesktopWindow) (2)获取当前顶层窗口的绘图设备(CWindowDC) (3)创建内存图像 (4)将当前顶层窗口图像复制到内存图像中 (5)保存图像
/**/
/* 参数: 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, 0 , 0 , rect.Width(), rect.Height(), winDC, 0 , 0 , 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:/
"
);
相关参考: CRectTracker CDC::DrawFocusRect CreateCompatibleBitmap http://blog.csdn.net/mynamelj/archive/2006/10/10/1329079.aspx