Capturing a screenshot with C#

First, we need a System.Drawing.Bitmap object. This holds the image data that is captured from the screen.

Bitmap b = new Bitmap(width, height);

In the constructor function, we specify the width and height, in integers, of the space we want to capture. This creates a bitmap object of that width and height with no data in it. If you are taking a full screen snapshot, use the width and height of your screen. (See System.Windows.SystemParameters)

We then need to create a System.Drawing.Graphics object that is linked to the Bitmap. This object will allow us to manipulate the image data inside the Bitmap.

Graphics g = Graphics.FromImage(b);

The final piece we need is a System.Drawing.Rectangle.

Rectangle r = new Rectangle(left, top, width, height);

In the constructor here, we put in the top-left origin (relative to the screen) of the space to be captured. It also requires the width and height of that space, which should be the same values as we put in the Bitmap constructor.

Now for the “magical” function.

g.CopyFromScreen(r.Left, r.Top, 0, 0, r.Size);

This is the function that actually gets the image data from your screen, and applies it to the Bitmap object. The first two values in this function specify at what point on the screen the data should begin to be copied from. The next two numbers specify at what point in the Bitmap object that data should be copied to. This allows you to offset the data in the image, but for this example we want the data to begin pasting in the top left corner of the Bitmap. The last value is essentially the width and height that we specified in the Rectangle constructor.

Now all we have left to do is write the Bitmap object to a file, and thankfully there is a built-in function for that too!

b.Save(path, ImageFormat.Png);

This is a fairly straightforward function. The “path” is a string that specifies where to save the file. It can be manually created or taken from a System.Windows.Forms.SaveFileDialog. The last value is a static property that specifies what image format to save the image in (make sure your “path” string has a matching file extension). See System.Drawing.Imaging.ImageFormat the different format options.

Here’s the full code.

Bitmap b = new Bitmap(width, height);
Graphics g = Graphics.FromImage(b);
Rectangle r = new Rectangle(left, top, width, height);
g.CopyFromScreen(r.Left, r.Top, 0, 0, r.Size);
b.Save(path, ImageFormat.Png);

That’s it! You are now able to take a screenshot of your desktop with C#!
If you have any suggestions or corrections, please leave a comment!