[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 }

 

posted @ 2014-03-03 11:14  beautifulzzzz  阅读(4925)  评论(4编辑  收藏  举报