How to take ScreenShot in C#

Friday, June 08, 2007

To create a screenshot in c# we need to use drawing api of the .net framework

First you have import System.Drawing.Imaging name space with following code...

using System.Drawing.Imaging;

here is the code in C# for screenshot.

int screenWidth = Screen.GetBounds(new Point(0, 0)).Width;
int screenHeight = Screen.GetBounds(new Point(0, 0)).Height;
Bitmap bmpScreenShot = new Bitmap(screenWidth, screenHeight);
Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
gfx.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight));

bmpScreenShot.Save("test.jpg", ImageFormat.Jpeg);


Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

3 comments:

Tommy Carlier said...

Your code will leak handles. You should really dispose the Graphics-object and the Bitmap at the end. Here's an alternative version:

Rectangle bounds = Screen.GetBounds(Point.Empty);
using(Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using(Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
bitmap.Save("test.jpg", ImageFormat.Jpeg);
}

Anonymous said...

Leak handles? This is managed code, why would you think that?

Anonymous said...

The "Leak Handles" version is funny. Like the guy is a paranoid c++ freak from 10 years back. If that code was required to avoid leaks, I would slit my wrists right now and get the pain of programming with memory management of my chest right now.

Google Translate

Search

Dotnetworld

Technet

Site Meter

Visitor Map

Locations of visitors to this page