//借鉴网上的文章:
HBITMAP CopyDCToBitmap(HDC hDC, LPRECT lpRect)
{
if(!hDC || !lpRect || IsRectEmpty(lpRect))
return NULL;
HDC hMemDC;
HBITMAP hBitmap, hOldBitmap;
int nX, nY, nX2, nY2;
int nWidth, nHeight;
nX = lpRect->left;
nY = lpRect->top;
nX2 = lpRect->right;
nY2 = lpRect->bottom;
nWidth = nX2 - nX;
nHeight = nY2 - nY;
hMemDC = CreateCompatibleDC(hDC);
hBitmap = CreateCompatibleBitmap(hDC, nWidth, nHeight);
hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap);
StretchBlt(hMemDC, 0, 0, nWidth, nHeight, hDC, nX, nY, nWidth, nHeight, SRCCOPY);
hBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap);
DeleteDC(hMemDC);
DeleteObject(hOldBitmap);
return hBitmap;
}
//抓屏,保存为图片
BOOL SaveBmp(HBITMAP bmp,char* path)
{
//把位图的信息保存到bmpinfo;
BITMAP bmpinfo;
GetObject(bmp,sizeof(BITMAP),&bmpinfo);
DWORD dwBmBitsSize = ((bmpinfo.bmWidth * 32+31)/32) * 4 * bmpinfo.bmHeight;
//位图文件头 14字节
BITMAPFILEHEADER bf;
bf.bfType = 0x4D42;
//BM
bf.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + dwBmBitsSize;
bf.bfReserved1 = 0;
bf.bfReserved2 = 0;
bf.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
//位图信息头
BITMAPINFOHEADER bi;
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = bmpinfo.bmWidth;
bi.biHeight = bmpinfo.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = 32;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 8;
bi.biClrImportant = 0;
//位图数据;
char* context = new char[dwBmBitsSize];
HDC dc = ::GetDC(NULL);
GetDIBits(dc, bmp, 0, bi.biHeight, context, (BITMAPINFO*)&bi, DIB_RGB_COLORS);
FILE* f = fopen(path,"wb");
fwrite((char*)&bf,sizeof(BITMAPFILEHEADER),1,f);
fwrite((char*)&bi,sizeof(BITMAPINFOHEADER),1,f);
fwrite(context,dwBmBitsSize,1,f);
fclose(f);
delete context;
::ReleaseDC(NULL,dc);
return 0;
}
void CaptureScreen()
{
int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
HWND hDesktopWnd = GetDesktopWindow();
HDC hDesktopDC = GetDC(hDesktopWnd);
HDC hCaptureDC = CreateCompatibleDC(hDesktopDC);
HBITMAP hCaptureBitmap =CreateCompatibleBitmap(hDesktopDC,
nScreenWidth, nScreenHeight);
SelectObject(hCaptureDC,hCaptureBitmap);
BitBlt(hCaptureDC,0,0,nScreenWidth,nScreenHeight,hDesktopDC,0,0,SRCCOPY);
SaveBmp(hCaptureBitmap, "F:\\capture.bmp"); //Place holder - Put your code
//here to save the captured image to disk
ReleaseDC(hDesktopWnd,hDesktopDC);
DeleteDC(hCaptureDC);
DeleteObject(hCaptureBitmap);
}
void CCaptureScreenDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
CaptureScreen();
}