//拷貝pWnd指向視窗的lpRect部分到檔案Dstfile中(BMP檔案格式)<br />CopyScreenToFile(CWnd *pWnd, CRect *lpRect, LPCTSTR Dstfile)<br />{<br /> if(!IsWindow(pWnd->GetSafeHwnd()))<br /> {<br /> AfxMessageBox("視窗控制代碼無效");<br /> return (FALSE);<br /> }</p><p> CDC *pDC = pWnd->GetDC();<br /> int Width = lpRect->Width();<br /> int Height = lpRect->Height();</p><p> CDC memDC;//記憶體DC<br /> memDC.CreateCompatibleDC(pDC);<br /> CBitmap memBitmap;//建立和螢幕相容的bitmap<br /> memBitmap.CreateCompatibleBitmap(pDC, Width, Height);<br /> memDC.SelectObject(&memBitmap);//將memBitmap選入記憶體DC<br /> memDC.BitBlt(0, 0, Width, Height,<br /> pDC, 0, 0,<br /> SRCCOPY);//複製螢幕映像到記憶體DC </p><p> //以下代碼儲存memDC中的位元影像到檔案<br /> BITMAP bmp;<br /> memBitmap.GetBitmap(&bmp);//獲得位元影像資訊 </p><p> DWORD bmpBytesSize = bmp.bmWidthBytes * bmp.bmHeight;</p><p> BITMAPFILEHEADER bfh = {0};//位元影像檔案頭<br /> bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);//到位元影像資料的位移量<br /> bfh.bfSize = bfh.bfOffBits + bmpBytesSize ;//檔案總的大小<br /> bfh.bfType = (WORD)0x4d42; </p><p> BITMAPINFOHEADER bih = {0};//位元影像資訊頭<br /> bih.biBitCount = bmp.bmBitsPixel;//每個像素位元組大小<br /> bih.biCompression = BI_RGB;<br /> bih.biHeight = bmp.bmHeight;//高度<br /> bih.biPlanes = 1;<br /> bih.biSize = sizeof(BITMAPINFOHEADER);<br /> bih.biSizeImage = bmpBytesSize;//映像資料大小<br /> bih.biWidth = bmp.bmWidth;//寬度 </p><p> BYTE * p = new byte[bmpBytesSize];//申請記憶體儲存位元影像資料<br /> GetDIBits(memDC.m_hDC,<br /> (HBITMAP) memBitmap.m_hObject, 0, Height,<br /> p,(LPBITMAPINFO) &bih, DIB_RGB_COLORS);//擷取位元影像資料 </p><p> for(DWORD i=0;i<bmpBytesSize-4;i)<br /> {<br /> BYTE tmp_uchar = p[i];<br /> p[i] = p[i+1];<br /> p[i+1] = p[i+2];<br /> p[i+2] = p[i+3];<br /> p[i+3] = tmp_uchar;<br /> i += 4;<br /> }</p><p> try<br /> {<br /> CFile fp(Dstfile,CFile::modeCreate | CFile::modeWrite);<br /> fp.Write(&bfh, sizeof(BITMAPFILEHEADER));//寫入位元影像檔案頭<br /> fp.Write(&bih, sizeof(BITMAPINFOHEADER));//寫入位元影像資訊頭<br /> fp.Write(p, bmp.bmWidthBytes * bmp.bmHeight);//寫入位元影像資料<br /> fp.Close();<br /> }<br /> catch( CFileException * e )<br /> {<br /> // Handle the file exceptions here.<br /> e->Delete();<br /> }</p><p> delete [] p; </p><p> return(true);<br />}<br />