Google
WWW Yariv Hammer's Code Site

Sunday, January 08, 2006

Print Screen And Save It to File

Introduction
A task which is quite common is to press the Print Screen button, and save the screen in Paint application as an Image file.
If you ever wondered how to perform such a task in .NET, here is the solution.

Solution
The following snippet of code does the trick:
------------------------------------------
SendKeys.Send("+{PRTSC}");
if (Clipboard.GetDataObject() != null)
{
   IDataObject data = Clipboard.GetDataObject();
   if (data.GetDataPresent(DataFormats.Bitmap))
   {
      Image image = (Image)data.GetData(DataFormats.Bitmap,true);
      image.Save("image.jpg",ImageFormat.Jpeg); // pick your format and path
   }
}
------------------------------------------

First we use the Sendkeys class. This class is not very famous, but it is quite nice. Whenever you want to emulate a key press you can call the Send method with the key you want to press. In our case we don't want just a key - we want to press the Print Screen key combined with the Ctrl key. "+" stands for Ctrl, and "PRTSC" stands for the Print Screen key.

From here on its all about the Clipboard. A press on Print Screen actually copies the screen image as it is into the clipboard. Instead of pasting it in Paint and saving it, we will use the Clipboard class. GetDataObject is the method to get the object currently in the clipboard. Unfortunately, we only get an IDataObject interface, without any knowledge of the actual type. So we call GetDataPresent to varify that the object is indeed an image. Once we are there, we call the GetData method which finally reveals the Image object. The Save method will store the image in any format we like and in any location.

0 Comments:

Post a Comment

<< Home

Feel free to use everything here. Add links to my site if you wish.

Do not copy anything to other sites without adding link to here.

All the contents of the site belong to Yariv Hammer.