窗口截图

窗口截图,可以获取遮挡窗口完整的图像,并保存到bmp文件中去。主要用到的函数中PrintWindow,VC6不支持该函数,请使用VS2008来编译。其它需求如平台要求请参考MSDN文档。

 1 void SaveHwndToBmpFile(HWND hWnd, LPCTSTR lpszPath)
 2 {
 3     HDC hDC = ::GetWindowDC(hWnd);
 4     ASSERT(hDC);
 5     
 6     HDC hMemDC = ::CreateCompatibleDC(hDC);
 7     ASSERT(hMemDC);
 8     
 9     RECT rc;
10     ::GetWindowRect(hWnd, &rc);
11 
12     HBITMAP hBitmap = ::CreateCompatibleBitmap(hDC, rc.right - rc.left, rc.bottom - rc.top);
13     ASSERT(hBitmap);
14     
15     HBITMAP hOldBmp = (HBITMAP)::SelectObject(hMemDC, hBitmap);
16     ::PrintWindow(hWnd, hMemDC, 0);
17 
18     BITMAP bitmap = {0};
19     ::GetObject(hBitmap, sizeof(BITMAP), &bitmap);
20     BITMAPINFOHEADER bi = {0};
21     BITMAPFILEHEADER bf = {0};
22 
23     CONST int nBitCount = 24;
24     bi.biSize = sizeof(BITMAPINFOHEADER);
25     bi.biWidth = bitmap.bmWidth;
26     bi.biHeight = bitmap.bmHeight;
27     bi.biPlanes = 1;
28     bi.biBitCount = nBitCount;
29     bi.biCompression = BI_RGB;
30     DWORD dwSize = ((bitmap.bmWidth * nBitCount + 31) / 32) * 4 * bitmap.bmHeight;
31 
32     HANDLE hDib = GlobalAlloc(GHND, dwSize + sizeof(BITMAPINFOHEADER));
33     LPBITMAPINFOHEADER lpbi = (LPBITMAPINFOHEADER)GlobalLock(hDib);
34     *lpbi = bi;
35 
36     ::GetDIBits(hMemDC, hBitmap, 0, bitmap.bmHeight, (BYTE*)lpbi + sizeof(BITMAPINFOHEADER), (BITMAPINFO*)lpbi, DIB_RGB_COLORS);
37 
38     try
39     {
40         CFile file;
41         file.Open(lpszPath, CFile::modeCreate | CFile::modeWrite);
42         bf.bfType = 0x4d42;
43         dwSize += sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
44         bf.bfSize = dwSize;
45         bf.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
46 
47         file.Write((BYTE*)&bf, sizeof(BITMAPFILEHEADER));
48         file.Write((BYTE*)lpbi, dwSize);
49         file.Close();
50     }
51     catch(CFileException* e)
52     {
53         e->ReportError();
54         e->Delete();
55     }
56 
57     GlobalUnlock(hDib);
58     GlobalFree(hDib);
59 
60     ::SelectObject(hMemDC, hOldBmp);
61     ::DeleteObject(hBitmap);    
62     ::DeleteObject(hMemDC);
63     ::ReleaseDC(hWnd, hDC);
64 }
65 
66 // 调用方法
67 HWND hWnd = ::FindWindow(NULL, _T("XXX"));
68 if(hWnd)
69 {
70    SaveHwndToBmpFile(hWnd, _T("F://12.bmp"));
71 }

文章来源:http://blog.csdn.net/visualeleven/article/details/6206715

posted @ 2014-07-25 14:27  GUOBBS  阅读(298)  评论(0编辑  收藏  举报