Programmatically grabbing a screenshot of the primary display

It’s sometimes difficult to explain to people what my job actually is. “I test Windows sound.” “Cool.  How does that work?”

A product like Windows has a lot of components that interact with each other.  If everything works, the user doesn’t know that most of these components even exist; everything is invisible and seamless.

Most testing involves the connection (“interface”) between two components.  “I test APIs.”  To the uninitiated, this is just a word.  It sounds like “I test wakalixes.”  “You test what, now?”

There are two interfaces which are easier to explain.  There’s the software-to-hardware interface, where the driver talks to the hardware.  “I test the HD Audio, USB Audio, and Bluetooth audio class drivers.”  “Huh?” “They make the speakers and the microphone work.”  “Oh, cool.  So you sit around and use Skype all day?”

But the easiest of all to explain is the user interface.  “I make sure that the Sound Recorder app, the volume slider, and the Sound control panel work.” “Oh, that!  I had this annoying problem once where…”

What does the test result for an invisible interface look like? A lot of logging.  “I expected this call to succeed; it returned this HRESULT.”  “I poked the hardware like this and got a bluescreen.”  “There seems to be an infinite loop here.”  Lots of text.


UI testing has logging too.  But with UI testing you can also… TAKE PICTURES!  A UI bug is a lot easier to understand (triage, and fix) if there’s a screenshot attached (preferably with a big red rectangle highlighting the problem.)

It is therefore valuable to have an automatable utility that can take a screenshot and dump it to a file.  Here’s one I cribbed together from the “Capturing an Image” sample code on

This version only captures the main display, and not secondary monitors (if any.)


screen_dc = GetDC(nullptr);
memory_dc = CreateCompatibleDC(screen);
rect = GetClientRect(GetDesktopWindow());
hbmp = CreateCompatibleBitmap(screen_dc, rect);
SelectObject(memory_dc, hbmp);
BitBlt(memory_dc, rect, screen_dc);
bmp = GetObject(hbmp);
bytes = allocate enough memory
bytes = GetDIBits(screen_dc, bmp, hbmp)
file = CreateFile();
WriteFile(bitmap header);

Browse source

Download screengrab.exe

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s