How to take a screenshot (Print Screen) using VB.Net

Capturing a screenshot in VB.Net is not at all a complex task. All it need is 3 lines of code.

Now you could easily display on a picture box:

Or Save it on your hard disk:

Now keep reading to see how it works, or just copy the code and go back to your work.

What is a Bitmap Object

A Bitmap is nothing but an object which stores the pixel data of an image. You can imagine it as an object which stores an array of all the pixels in the image.

What is a Graphics Object

A Graphics Object can be considered as a surface where you draw on. You can use a Graphics Object to draw on any display device. A display device may be a bitmap, a printer, the entire screen, or a window. You can draw to any of these devices in the same way using a Graphics Object.

Now see the step by step procedure to capture the screen

Step 1: Creating a Bitmap object

The first step is creating an empty bitmap object. This is where we store our captured screen image. An empty Bitmap Object can be created by passing the width and height of Bitmap to its constructor. In our case the width and height should be same as that of the screen. So we pass the screen’s width and height as the parameters.

Step 2: Creating a Graphics object

Now we need to create Graphics Object to draw to our Bitmap. This is done by invoking Graphics.FromImage() function.

We’ve passed the Bitmap we created in previous step, as the parameter to Graphics.FromImage() function. Now we have the Graphics Object in our hand, so we can easily draw to the it.

Step 3: Capturing the Screen

Now its time to capture the screen. We do this by calling CopyFromScreen() function which copies the color data of a rectangle of pixels from the screen to the Graphics Object.

The 3 parameters passed are The point on the source (screen) where the copying starts. The point on the destination (Graphics) where the drawing starts. The size of the rectangle to copy.

Saving the image

As said before, the Bitmap can be saved simply by calling Bitmap.save() function with the file name as parameter. You could also specify the ImageFormat such as jpeg, png etc. Here are some examples

The second parameter can be any one of the formats specified in the System.Drawing.Imaging.ImageFormat class.

References

Hope that might be enough for anyone to understand how it works. Here are a few links to msdn where you could read more :

Leave a Reply

Your email address will not be published. Required fields are marked *