PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags)

Its a lazy Sunday morning so what else would I be doing but reading through the updated parts of the Win32 API documentation (for Windows XP). After being inspired by this post I started to think about some software to support manual screen verification where screenshots can be compared by a human against reference shots.

In the past I have done some fairly gruesome code to take a screenshot which is why I was thrilled when I came across the PrintWindow function (new in XP). This function takes a handle to a window to take the shot from and a device context to copy it to (with some flags). The beauty of this function is that it is exceptionally fast. The routines that I had written in the past were quite slow and caused the UI to “lock-up” for a fraction of a second.


private static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);

I did a quick test of the function with the following code (from within a Form).

Bitmap bm = new Bitmap(1024, 768);

Graphics g = Graphics.FromImage(bm);

IntPtr hdc = g.GetHdc();

Form1.PrintWindow(this.Handle, hdc, 0);




this.pictureBox1.Image = bm;

Just be aware that I haven’t tested this for memory leaks or anything, and obviously if something crashes half way through the routine some of the resources haven’t been cleaned up (so don’t go and slap this into your application just yet cowboy!). One of the things I tell my clients is that you need to maximise the amount of diagnostics that you get back from your application when things go wrong. A stack trace is helpful, but so is a bunch of screenshots. Ever had that conversation with an end-user when you ask them what they were doing and they say “I dunno?”. Grrrr.

6 thoughts on “PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags)

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s