[MFC] MFC 獲取指定窗口截圖(大小可調)


 1 void screenShot(CRect rect,int left,int top,char *name){//截取窗口的大小,位置,名字(保存在默認路徑下)
 2     CBitmap*  m_pBitmap;                                                      // 加入類成員
 3     CFrameWnd* pMainFrame = (CFrameWnd*)AfxGetMainWnd();                     // 獲得截圖窗口的指針,默認為主窗口,可以更改為其他的窗口。
 4        CPaintDC   dc(pMainFrame); 
 5     
 6     m_pBitmap=new   CBitmap;   
 7     m_pBitmap->CreateCompatibleBitmap(&dc,rect.Width(),rect.Height());   
 8 
 9     CDC   memDC;  
10     memDC.CreateCompatibleDC(&dc); 
11     CBitmap memBitmap, *oldmemBitmap;                                        // 建立和屏幕兼容的bitmap
12     memBitmap.CreateCompatibleBitmap(&dc, rect.Width(),rect.Height());
13     
14     oldmemBitmap = memDC.SelectObject(&memBitmap);//將memBitmap選入內存DC
15     memDC.BitBlt(0, 0, rect.Width(),rect.Height(), &dc,left, top, SRCCOPY);  // 調解高度寬度
16     BITMAP bmp;
17     memBitmap.GetBitmap(&bmp);                                               // 獲得位圖信息 
18     
19     FILE *fp = fopen(name, "w+b");
20     
21     BITMAPINFOHEADER bih = {0};                                              // 位圖信息頭
22     bih.biBitCount = bmp.bmBitsPixel;                                        // 每個像素字節大小
23     bih.biCompression = BI_RGB;
24     bih.biHeight = bmp.bmHeight;                                             // 高度
25     bih.biPlanes = 1;
26     bih.biSize = sizeof(BITMAPINFOHEADER);
27     bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;                       // 圖像數據大小
28     bih.biWidth = bmp.bmWidth;                                               // 寬度
29     
30     BITMAPFILEHEADER bfh = {0};                                              // 位圖文件頭
31     bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);     // 到位圖數據的偏移量
32     bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;            // 文件總的大小
33     bfh.bfType = (WORD)0x4d42;
34     
35     fwrite(&bfh, 1, sizeof(BITMAPFILEHEADER), fp);                           //寫入位圖文件頭
36     
37     fwrite(&bih, 1, sizeof(BITMAPINFOHEADER), fp);                           //寫入位圖信息頭
38     
39     byte * p = new byte[bmp.bmWidthBytes * bmp.bmHeight];                    //申請內存保存位圖數據
40     
41     GetDIBits(memDC.m_hDC, (HBITMAP) memBitmap.m_hObject, 0, rect.Height(), p, 
42     (LPBITMAPINFO) &bih, DIB_RGB_COLORS);                                    //獲取位圖數據
43     
44     fwrite(p, 1, bmp.bmWidthBytes * bmp.bmHeight, fp);                       //寫入位圖數據
45     delete [] p;    
46     fclose(fp);
47     memDC.SelectObject(oldmemBitmap);
48     memDC.DeleteDC();
49 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM