MFC截屏生成bmp格式图片

void ScreenToBmp(CWnd*m_hwnd)
{
CRect rc;
m_hwnd->GetClientRect(&rc);
CClientDC dc(m_hwnd); //m_hwnd 创建客户区绘制内存

int iBitPerPixel = dc.GetDeviceCaps(BITSPIXEL);//像素相连颜色位数  
int iWidth = rc.Width(); //宽
int iHeight = rc.Height(); //高 
CDC memDC; //绘图对象
memDC.CreateCompatibleDC(&dc);

CBitmap memBitmap, *oldBitmap;

memBitmap.CreateCompatibleBitmap(&dc, iWidth, iHeight);
oldBitmap = memDC.SelectObject(&memBitmap);

memDC.BitBlt(0, 0, iWidth, iHeight, &dc, 0, 0, SRCCOPY);

BITMAP bmp;
memBitmap.GetBitmap(&bmp);

CString str; //获取系统时间 
CTime tm;
tm = CTime::GetCurrentTime();
str = tm.Format(L"%Y-%m-%d-%H-%M-%S");
str = _T(".//ShotPic//") + str + _T(".bmp");
char *pChar;
pChar = CstringToChar(str, pChar);
CreateDirectoryA(".//ShotPic", NULL);
FILE *fp;
fopen_s(&fp, pChar, "wb"); //".//ShotPic//test2.bmp"

BITMAPINFOHEADER bih; //位图信息头 
memset(&bih, 0, sizeof(bih));
bih.biBitCount = bmp.bmBitsPixel;
bih.biCompression = BI_RGB;//表示不压缩  
bih.biHeight = bmp.bmHeight;
bih.biPlanes = 1; //位平面数,必须为1  
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;
bih.biWidth = bmp.bmWidth;

BITMAPFILEHEADER bfh; //位图文件头 
memset(&bfh, 0, sizeof(bfh));
bfh.bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;
bfh.bfType = (WORD)0x4d42;//必须表示"BM"  

fwrite(&bfh, 1, sizeof(BITMAPFILEHEADER), fp);
fwrite(&bih, 1, sizeof(bih), fp);

byte * p = new byte[bmp.bmWidthBytes * bmp.bmHeight];
GetDIBits(memDC.m_hDC, (HBITMAP)memBitmap.m_hObject, 0, iHeight, p, (LPBITMAPINFO)&bih, DIB_RGB_COLORS);
fwrite(p, 1, bmp.bmWidthBytes * bmp.bmHeight, fp);
delete[] p;

fclose(fp);

memDC.SelectObject(oldBitmap);

return;
}

你可能感兴趣的:(MFC截屏生成bmp格式图片)