窗口截图(可指定HWND窗口句柄)(三篇文章)

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

http://blog.csdn.net/visualeleven/article/details/6202796

http://blog.csdn.net/visualeleven/article/details/6206715

http://blog.csdn.net/visualeleven/article/details/6093484