1. 程式人生 > >工作問題積累(六)截圖並且儲存 VC++

工作問題積累(六)截圖並且儲存 VC++

void CQueenMainDlg::SavePicture(CString SaveFileName)
{
 BeginWaitCursor();

 BYTE *pPicData = NULL;
 //CDC *pDC = GetDC();                        //1.當前顯示的客戶端視窗
 CDC *pDC = CDC::FromHandle(::GetDC(NULL));   //2.整個螢幕
 HDC pScrDC = pDC->GetSafeHdc();
 HDC pMemDC = CreateCompatibleDC(pScrDC);

 int nBitsPixel = pDC->GetDeviceCaps(BITSPIXEL);
 //CRect rcWndRect;
 int width = pDC->GetDeviceCaps(HORZRES);
 int hight = pDC->GetDeviceCaps(VERTRES);

 DWORD nImageSize = width*hight*nBitsPixel/8;
 pPicData = new BYTE[nImageSize];

 BITMAPINFOHEADER  bmpinfoheader;
 memset(&bmpinfoheader,0,sizeof(bmpinfoheader));
 bmpinfoheader.biSize = sizeof(bmpinfoheader);
 bmpinfoheader.biWidth = width;
 bmpinfoheader.biHeight = hight;
 bmpinfoheader.biBitCount = nBitsPixel;
 bmpinfoheader.biCompression = BI_RGB;
 bmpinfoheader.biPlanes = 1;
 bmpinfoheader.biSizeImage = nImageSize;

 //建立一個與螢幕裝置描述表相容的點陣圖
 HBITMAP hNewBit = CreateCompatibleBitmap(pScrDC,width,hight);

 //把新點陣圖放到記憶體裝置描述表中
 HBITMAP hOldBit = (HBITMAP)SelectObject(pMemDC,hNewBit);

 //把螢幕裝置表拷貝到記憶體裝置表中
 StretchBlt(pMemDC,0,0,width,hight,pScrDC,0,0,width,hight,SRCCOPY);

 //取得點陣圖資料
 GetDIBits(pMemDC,hNewBit,0,hight,pPicData,(LPBITMAPINFO)&bmpinfoheader,DIB_RGB_COLORS);

 //得到螢幕點陣圖的控制代碼
 SelectObject(pMemDC,hOldBit);

 //釋放
 ReleaseDC(pDC);
 DeleteDC(pMemDC);
 DeleteObject(hNewBit);


 if (pPicData)
 {
  DWORD nLineLen = (width*nBitsPixel+31)/32*4;
  DWORD nColSize = sizeof(RGBQUAD)*((nBitsPixel <= 8) ? 1<<nBitsPixel:0);
  DWORD nImgSize = sizeof(BITMAPINFOHEADER) + nColSize + (DWORD)(UINT)nLineLen*(DWORD)(UINT)hight;

  BITMAPFILEHEADER bmpfileheader;
  bmpfileheader.bfType = MAKEWORD('B','M');
  bmpfileheader.bfSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+nImgSize;
  bmpfileheader.bfReserved1 = bmpfileheader.bfReserved2 = 0;
  bmpfileheader.bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);

  BITMAPINFOHEADER BmpInfoHead;
  memset(&BmpInfoHead,0,sizeof(BITMAPINFOHEADER));
  BmpInfoHead.biSize = sizeof(BITMAPINFOHEADER);
  BmpInfoHead.biWidth = width;
  BmpInfoHead.biHeight = hight;
  BmpInfoHead.biBitCount = nBitsPixel;
  BmpInfoHead.biCompression = BI_RGB;
  BmpInfoHead.biPlanes = 1;
  BmpInfoHead.biSizeImage = nImgSize-sizeof(BITMAPINFOHEADER)-nColSize;
  BmpInfoHead.biXPelsPerMeter = BmpInfoHead.biYPelsPerMeter = 0;
  BmpInfoHead.biClrUsed = (nBitsPixel <= 8) ? 1<<nBitsPixel:0;
  BmpInfoHead.biClrImportant = 0;


  CFile file;
  CString strXmlFile = theApp.m_strAppPath;
  strXmlFile += _T("skin\\");
  file.SetFilePath(strXmlFile);
  if (file.Open(SaveFileName,CFile::modeCreate | CFile::modeWrite))
  {
   file.Write(&bmpfileheader,sizeof(bmpfileheader));
   file.Write(&BmpInfoHead,sizeof(BmpInfoHead));
   file.Write(pPicData,nImgSize);
   file.Close();
  }
  delete []pPicData;

 }
 EndWaitCursor();
 SendTrack();
 

 

}