2010-07-20 11 views

Respuesta

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

Esto funciona en todas las ventanas basadas en nt de Windows NT4 a Windows 7. – Woody

+6

¿Por qué está utilizando CreateDC y no solo GetDC (NULL)? – Anders

+0

Honestamente, no lo he visto por un tiempo, este es un código bastante antiguo que he estado usando en una aplicación. ¡Funciona en todo, así que nunca volví a hacerlo! Si GetDC sería mejor, puedo enmendar la respuesta. – Woody

3

Hay una muestra de MSDN, Capturing an Image, para capturar un HWND arbitrario a un DC (puede intentar pasar el resultado de GetDesktopWindow a esto). Pero no sé qué tan bien funcionará esto con el nuevo compositor de escritorio en Vista/Windows 7.

24
  1. Utilice GetDC(NULL); para obtener un DC para toda la pantalla.
  2. Utilice CreateCompatibleDC para obtener un DC compatible.
  3. Utilice CreateCompatibleBitmap para crear un mapa de bits para contener el resultado.
  4. Utilice SelectObject para seleccionar el mapa de bits en el DC compatible.
  5. Utilice BitBlt para copiar de la pantalla DC al DC compatible.
  6. Deseleccione el mapa de bits del DC compatible.

Cuando crea el mapa de bits compatible, quiere que sea compatible con la pantalla DC, no con el DC compatible.

+1

¿Qué pasa con los sistemas de pantalla doble? ¿Disparo de ambas pantallas? – i486

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