C# Get Desktop Screenshot

I found this feature while looking inside Graphics class and since it was so simple to use, I decided to post it here.
As I said, it doesn’t require more than 15 lines of code – this function: Graphics.CopyFromScreen does all the ‘hard work’ so we only need to put this into a Bitmap and save/display it.

To the code!

There are 3 steps that you need to follow:
– create a Bitmap that’s exactly the screen’s size
– using that Bitmap, create a Graphics object (Graphics.FromImage)
– use CopyFromScreen() and save the Bitmap.
The code looks like this:
C#
1
2
3
4
5
6
7
8
9
10
private void takeScreenShot()
{
    Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
    using (Graphics g = Graphics.FromImage(bmp))
    {
        g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
        bmp.Save("screenshot.png");  // saves the image
    }                
}
 
Previous
Next Post »