如何在Windows应用程序中截取屏幕截图?

问题描述:

如何使用Win32截取当前屏幕截图?如何在Windows应用程序中截取屏幕截图?

+2

捕捉屏幕 http://www.codeproject.com/Articles/5051/Various-methods-for-capturing-the-screen – hB0 2012-07-06 11:44:19

+1

这里是我的编译要点各种方法/gist.github.com/rdp/9821698 – rogerdpack 2014-03-27 23:45:42

// 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 
+0

这适用于从Windows NT4到Windows 7的所有基于NT的窗口。 – Woody 2010-07-20 15:11:10

+6

为什么使用CreateDC而不仅仅是GetDC(NULL)? – Anders 2010-07-21 03:57:43

+0

老实说,我没有看过它一段时间,这是代码从我一直在应用程序中使用的方式。它适用于所有事情,所以我从来没有回过头去看它! 如果GetDC更好,我可以赞扬答案。 – Woody 2010-07-21 08:04:15

有一个MSDN示例Capturing an Image用于捕获到DC的任意HWND(您可以尝试将GetDesktopWindow的输出传递给此DC)。但是,在Vista/Windows 7上的新桌面排版工具下,这种效果会有多好,我不知道。

  1. 使用GetDC(NULL);可以获得整个屏幕的DC。
  2. 使用CreateCompatibleDC来获得兼容的DC。使用CreateCompatibleBitmap创建一个位图来保存结果。使用SelectObject来选择位图到兼容的DC中。
  3. 使用BitBlt从屏幕DC复制到兼容的DC。
  4. 取消选择兼容DC中的位图。

当您创建兼容位图时,您希望它与屏幕DC兼容,而不兼容DC。 HTTPS:/

+1

双显示系统呢?两个屏幕的镜头? – i486 2016-01-12 22:23:46

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); 
}