Wednesday, July 7, 2010

Taking Screenshots with C#

Today I want to explain how to take a screenshot with the programming language C#.
I will immediately post the source code, which I will explain afterwards:
private Bitmap TakeScreenshot(bool onlyForm)
{
int StartX, StartY;
int Width, Height;

StartX = (onlyForm) ? (this.Left) : (0);
StartY = (onlyForm) ? (this.Top) : (0);
Width = (onlyForm) ? (this.Width) : (Screen.PrimaryScreen.Bounds.Width);
Height = (onlyForm) ? (this.Height) : (Screen.PrimaryScreen.Bounds.Height);

Bitmap Screenshot = new Bitmap(Width, Height);
Graphics G = Graphics.FromImage(Screenshot);

G.CopyFromScreen(StartX, StartY, 0, 0, new Size(Width, Height), CopyPixelOperation.SourceCopy);
return Screenshot;
}
The function used to take a screenshot is CopyFromScreen() of the class Graphics.
The overloadment used here takes 6 parameters. The first two ones describe the top left corner of the screen area which is supposed to be copied.
As parameter 3 and 4 are here given 0s. These parameters describe the top left corner of the screenshot on the resulting bitmap. Are here given different values, the screenshot is moved about these in the Bitmap.
The 5th parameter describes the size of the screenshot, the 6th one says, that the points are to be copied true to original.
The function TakeScreenshot() expects a boolean variable as parameter. Is it set to false, the complete screen is printed, otherwise only the active form is printed (the canvas size and the coordinates StartX and StartY are set according to the form).
If you are not sure about the meaning of the question marks in the code, check this post out.
With this code, a screenshot of the whole screen can for example be taken and copied to a PictureBox as follows:
pictureBox1.Image = TakeScreenshot(false);

No comments:

Post a Comment