最后,贴点代码吧:
用GDI 和GDI+混合编写的屏幕截图的代码
int m_iScreenCX; int m_iScreenCY; m_iScreenCX=::GetSystemMetrics(SM_CXSCREEN); m_iScreenCY=::GetSystemMetrics(SM_CYSCREEN); CWindowDC dc(this->GetDesktopWindow()); // 在对话框中调用 CBitmap m_screenBitmap; // 用于保存图像的对象 m_screenBitmap.CreateCompatibleBitmap(&dc,m_iScreenCX,m_iScreenCY); CDC memDC; memDC.CreateCompatibleDC(&dc); CBitmap *pOldBitmap = memDC.SelectObject(&m_screenBitmap); memDC.BitBlt(0,0,m_iScreenCX,m_iScreenCY,&dc,0,0,SRCCOPY); // 保存屏幕截图 memDC.SelectObject(pOldBitmap); Bitmap bitmap((HBITMAP)m_screenBitmap.GetSafeHandle(),NULL); CLSID picClsid; // 同样也可保存至PNG文件 GetEncoderClsid(L"image/bmp", &picClsid); //GetEncoderClsid(L"image/png", &picClsid); bitmap.Save(L"screen.bmp", &picClsid, NULL); //bitmap.Save(L"screen.png", &picClsid, NULL);还有个用GDI+写的SaveBitmapToFile 好处在于可以直接保存成其他格式如PNG 、GIF、 JPG等
int SaveBitmapToFile(HBITMAP hBitmap, LPSTR lpFileName) { Bitmap savedBitmap(hBitmap,NULL); CLSID bmpClsid; GetEncoderClsid(L"image/bmp", &bmpClsid); CString strFileName(lpFileName); size_t bufSize,strSize; strSize=strFileName.GetLength(); bufSize=MultiByteToWideChar(CP_ACP,NULL,strFileName.GetBuffer(strSize),strSize,NULL,0); if(bufSize) { wchar_t * pwStrFileName = new wchar_t[bufSize+1]; if(MultiByteToWideChar(CP_ACP, NULL,strFileName.GetBuffer(strSize),strSize, pwStrFileName, bufSize)) { pwStrFileName[bufSize]=L'\0'; savedBitmap.Save(pwStrFileName, &bmpClsid, NULL); if(pwStrFileName) delete [] pwStrFileName; return TRUE; }else return FALSE; }else return FALSE; } int GetEncoderClsid(const WCHAR* format, CLSID* pClsid) { UINT num = 0; // number of image encoders UINT size = 0; // size of the image encoder array in bytes ImageCodecInfo* pImageCodecInfo = NULL; GetImageEncodersSize(&num, &size); if(size == 0) return -1; // Failure pImageCodecInfo = (ImageCodecInfo*)(malloc(size)); if(pImageCodecInfo == NULL) return -1; // Failure GetImageEncoders(num, size, pImageCodecInfo); for(UINT j = 0; j < num; ++j) { if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 ) { *pClsid = pImageCodecInfo[j].Clsid; free(pImageCodecInfo); return j; // Success } } free(pImageCodecInfo); return -1; // Failure }