拷贝屏幕到位图的函数

来源:互联网 发布:什么是客户端编程 编辑:程序博客网 时间:2024/06/05 15:47

HBITMAP CCatchScreenDlg::CopyScreenToBitmap(LPRECT lpRect,BOOL bSave)
//lpRect 代表选定区域
{
 HDC       hScrDC, hMemDC;     
 // 屏幕和内存设备描述表
 HBITMAP    hBitmap, hOldBitmap;  
 // 位图句柄
 int       nX, nY, nX2, nY2;     
 // 选定区域坐标
 int       nWidth, nHeight;
 
 // 确保选定区域不为空矩形
 if (IsRectEmpty(lpRect))
  return NULL;
 //为屏幕创建设备描述表
 hScrDC = CreateDC("DISPLAY", NULL, NULL, NULL);

 //为屏幕设备描述表创建兼容的内存设备描述表
 hMemDC = CreateCompatibleDC(hScrDC);
 // 获得选定区域坐标
 nX = lpRect->left;
 nY = lpRect->top;
 nX2 = lpRect->right;
 nY2 = lpRect->bottom;

 //确保选定区域是可见的
 if (nX < 0)
  nX = 0;
 if (nY < 0)
  nY = 0;
 if (nX2 > m_xScreen)
  nX2 = m_xScreen;
 if (nY2 > m_yScreen)
  nY2 = m_yScreen;
 nWidth = nX2 - nX;
 nHeight = nY2 - nY;
 // 创建一个与屏幕设备描述表兼容的位图
 hBitmap = CreateCompatibleBitmap
  (hScrDC, nWidth, nHeight);
 // 把新位图选到内存设备描述表中
 hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap);
 // 把屏幕设备描述表拷贝到内存设备描述表中
 if(bSave)
 {
  CDC dcCompatible;
  dcCompatible.CreateCompatibleDC(CDC::FromHandle(hMemDC));
  dcCompatible.SelectObject(m_pBitmap);
       
  BitBlt(hMemDC, 0, 0, nWidth, nHeight,
   dcCompatible, nX, nY, SRCCOPY);

 }
 else
 {
  BitBlt(hMemDC, 0, 0, nWidth, nHeight,
   hScrDC, nX, nY, SRCCOPY);
 }

 hBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap);
 //得到屏幕位图的句柄
 //清除
 DeleteDC(hScrDC);
 DeleteDC(hMemDC);
 // 返回位图句柄
 if(bSave)
 {
    
  if (OpenClipboard())
  {
        //清空剪贴板
        EmptyClipboard();
        //把屏幕内容粘贴到剪贴板上,
        //hBitmap 为刚才的屏幕位图句柄
        SetClipboardData(CF_BITMAP, hBitmap);
        //关闭剪贴板
        CloseClipboard();
      }
 }
 return hBitmap;
}

 

调用时可以这样:

 

 //获取屏幕分辩率
 m_xScreen = GetSystemMetrics(SM_CXSCREEN);
 m_yScreen = GetSystemMetrics(SM_CYSCREEN);
 //截取屏幕到位图中
 CRect rect(0, 0,m_xScreen,m_yScreen);
 m_pBitmap=CBitmap::FromHandle(CopyScreenToBitmap(&rect));