Ever since I can remember, I've been fascinated by the print screen keyboard command. Just exactly how did it capture an image? What strange and powerful API was I missing? Well, after a few months of coding, and getting familiar with the Windows platform, I realized that I could easily code my own screen capture, without relying upon the print screen keyboard command. [An extended version of Mark's article appears on The Code Project.]
Using just a few API calls and some GDI+, we can recreate the functionality that the print screen command offers. With one advantage: We're not going to touch the Window's Clipboard. Too many times, do I see improper usage of the clipboard, and in my opinion, slapping a big fat image onto it, erasing whatever you had on their before with no warning, is just a bad idea.
When you approach a project like this, it is important to start with an understanding of device contexts. Device contexts are just generic ways to represent devices, or things you can draw on or interact with graphically. This is hugely over simplified, but for the sake of brevity, let's just go with that for now. You can get device context's, or dc's as they are commonly referred to, from images, windows, monitors, and even printers. Every window has them, and they can be used for drawing.
Everything you see on your screen is being drawn upon a device context. The desktop, every window, your taskbar, and anything you see. You can draw upon them, or copy what they have drawn upon them. If you can get a hold of them, you can pretty much draw or steal whatever you want graphically speaking. Working with device contexts is fast, and both GDI and GDI+ are based upon using them.
What's all that mean? Well, in the case of capturing the screen, we know that somewhere window's is drawing upon a device context, so that we can see it. In fact, there's one for each monitor you have attached to your system, and that desktop that you are seeing on it, is being drawn on that monitor's device context. All we have to do is grab a hold of that device context, create another one of our own, and copy the screen's device context image data to our own, and we've got a screen capture.
Using our knowledge of the .NET framework, and some additional knowledge of the Windows APIs, we can pretty effectively duplicate how the print screen command works. A method that used as an example will enumerate all of the monitors attached to the system, figure out just how big the combinded desktop is, and then copy what each monitor has displayed on it into a final bitmap image. Click here to access the full version of this article on The CodeProject site with code.
Dig Deeper on ASP.NET development best practices
Related Q&A from Mark Belles
This expert response shows how to access VB .NET Windows control on the client side. Continue Reading
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.