views:

65

answers:

3

how can i make screen-shots of the local pc screen with win32 c++?

A: 

There is MSDN sample code here for capturing an arbitrary HWND to a DC (you could try passing the output from GetDesktopWindow to this). But how well this will work under the new desktop compositor on Vista/Windows 7, I don't know.

Bob Moore
A: 
  1. Use GetDC(NULL); to get a DC for the entire screen.
  2. Use CreateCompatibleDC to get a compatible DC.
  3. Use CreateCompatibleBitmap to create a bitmap to hold the result.
  4. Use SelectObject to select the bitmap into the compatible DC.
  5. Use BitBlt to copy from the screen DC to the compatible DC.
  6. Deselect the bitmap from the compatible DC.

When you create the compatible bitmap, you want it compatible with the screen DC, not the compatible DC.

Jerry Coffin
+2  A: 
// get the device context of the screen
hScreenDC = CreateDC("DISPLAY", NULL, NULL, NULL);     
// and a device context to put it in
hMemoryDC = CreateCompatibleDC(hScrDC);

x = GetDeviceCaps(hScreenDC, HORZRES);
y = GetDeviceCaps(hScreenDC, VERTRES);

// maybe worth checking these are positive values
hBitmap = CreateCompatibleBitmap(hScreenDc, x, y);

// get a new bitmap
hOldBitmap = SelectObject(hMemoryDC, hBitmap)

BitBlt(hMemoryDC, 0, 0, width, height, hScreenDC, 0, 0, SRCCOPY);
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
Woody
This works on all nt based windows from Windows NT4 to Windows 7.
Woody
@Woody: Why are you using CreateDC and not just GetDC(NULL)?
Anders
Honestly I haven't looked at it for a while, this is code from quite a way back which I have been using in an application. It works in everything so I have never gone back to it!If GetDC would be better, I can ammend the answer.
Woody