我怎样才能在Windows应用程序截图?

如何使用Win32截取当前屏幕?

// get the device context of the screen HDC hScreenDC = CreateDC("DISPLAY", NULL, NULL, NULL); // and a device context to put it in HDC hMemoryDC = CreateCompatibleDC(hScreenDC); int width = GetDeviceCaps(hScreenDC, HORZRES); int height = GetDeviceCaps(hScreenDC, VERTRES); // maybe worth checking these are positive values HBITMAP hBitmap = CreateCompatibleBitmap(hScreenDC, width, height); // get a new bitmap HBITMAP hOldBitmap = (HBITMAP) SelectObject(hMemoryDC, hBitmap); BitBlt(hMemoryDC, 0, 0, width, height, hScreenDC, 0, 0, SRCCOPY); hBitmap = (HBITMAP) SelectObject(hMemoryDC, hOldBitmap); // clean up DeleteDC(hMemoryDC); DeleteDC(hScreenDC); // now your image is held in hBitmap. You can save it or do whatever with it 
  1. 使用GetDC(NULL); 为整个屏幕获得一个DC。
  2. 使用CreateCompatibleDC来获得兼容的DC。
  3. 使用CreateCompatibleBitmap创build一个位图来保存结果。
  4. 使用SelectObject将位图select到兼容的DC中。
  5. 使用BitBlt从屏幕DC复制到兼容的DC。
  6. 从兼容的DC中取消select位图。

当您创build兼容的位图时,您希望它与屏幕DC兼容,而不兼容DC。

 void GetScreenShot(void) { int x1, y1, x2, y2, w, h; // get screen dimensions x1 = GetSystemMetrics(SM_XVIRTUALSCREEN); y1 = GetSystemMetrics(SM_YVIRTUALSCREEN); x2 = GetSystemMetrics(SM_CXVIRTUALSCREEN); y2 = GetSystemMetrics(SM_CYVIRTUALSCREEN); w = x2 - x1; h = y2 - y1; // copy screen to bitmap HDC hScreen = GetDC(NULL); HDC hDC = CreateCompatibleDC(hScreen); HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h); HGDIOBJ old_obj = SelectObject(hDC, hBitmap); BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, x1, y1, SRCCOPY); // save bitmap to clipboard OpenClipboard(NULL); EmptyClipboard(); SetClipboardData(CF_BITMAP, hBitmap); CloseClipboard(); // clean up SelectObject(hDC, old_obj); DeleteDC(hDC); ReleaseDC(NULL, hScreen); DeleteObject(hBitmap); } 

有一个MSDN示例捕获图像 ,用于捕获到DC的任意HWND(您可以尝试从GetDesktopWindow传递输出到此)。 但是,在Vista / Windows 7的新桌面排版工具下,这样做还有多好,我不知道。