2010-07-20 127 views

回答

49
// 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

3

有一個MSDN示例Capturing an Image用於捕獲到DC的任意HWND(您可以嘗試將GetDesktopWindow的輸出傳遞給此DC)。但是,在Vista/Windows 7上的新桌面排版工具下,這種效果會有多好,我不知道。

24
  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

23
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); 
} 
相關問題