MFC获取当前控件句柄,并创建BMP位图文件保存

void CTest_PicShotDlg::ScreenShot(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);
    CreateDirectoryA( ".//ShotPic", NULL );
    FILE *fp = fopen(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 ;
}
关于BMP位图文件格式,可参考网上资料; 点击打开链接

猜你喜欢

转载自blog.csdn.net/qq_36568418/article/details/80026838