Grabbing a screenshot.

So, I want to nab a screenshot of the desktop, as a bitmap. But, I need to store it in a container, probably a "struct" and pass it around my main application like it's a hotcake. How can I access the bitmap information now that I should have a screenshot? What should a struct have in it for holding this crap? I need the data to be fairly mobile, meaning I have the bitmap data, in a buffer I have immediate access to, any thoughts?

using namespace std;

-Palette data (If 8 bit bitmap)
-Pixel/image data

The GDI revolves around an object called the Device Context (DC), represented by the data type HDC (Handle to Device Context).
An HDC is basically a handle to something you can draw on; it can represent the entire screen, an entire window,
the client area of a window, a bitmap stored in memory, or a printer.
The nice part is that you don't even need to know which one it refers to, you can use it basically the same way,
which is especially handy for writing custom drawing functions which you can then use on any of these devices without changing
it for each one.

int main()
int width=GetSystemMetrics(SM_CXSCREEN);
int height=GetSystemMetrics(SM_CYSCREEN);

HDC screen_dc=CreateCompatibleDC(0);
HBITMAP bitmap_h=CreateCompatibleBitmap(GetDC(0),width,height);
BITMAP bitmap;

// join em up
HBITMAP old_bitmap_h = (HBITMAP)SelectObject(screen_dc, bitmap_h);

//Copy From the screen to my bitmap
BitBlt( screen_dc, 0, 0, width, height, GetDC(0), 0, 0, SRCCOPY ); // the name "screen_dc" may be misleading, but it's the bitmap

//get object info, bad name of "GetObject"
GetObject( bitmap_h, sizeof(BITMAP), &bitmap );

cout << bitmap.bmBits << endl;
cout << bitmap.bmType << endl;
cout << bitmap.bmBitsPixel << endl;
cout << bitmap.bmWidth << endl;

cout << "Last error: " << GetLastError() << endl;

//Restore bitmap to DC
SelectObject(screen_dc, old_bitmap_h );

return 0;


  • [color=Blue]If you pass the bitmap handle around, but within one process, then it is OK, however, it cannot be passed between two processes.

    Also, handle returned by GetDC() usually needs a ReleaseDC() - otherwise, GDI leaks will occur and application fails after some time. I suggest making just one call to GetDC() and once the screen is captured - ReleaseDC() it.[/color]
  • Okay, the resource leak is a good catch, but I can't pass the handle around, I need the actual data in a way I can work with it, stored in-memory, like a pointer to the data... I will be sending this across the internet in the application I'm making.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!