How to capture the current screen using Windows Forms
Posted by: Suprotim Agarwal ,
on 2/26/2008,
in
Category WinForms & WinRT
Abstract: The Graphics class exposes a method called CopyFromScreen(). According to MSDN, this method performs a bit-block transfer of the color data, corresponding to a rectangle of pixels, from the screen to the drawing surface of the Graphics. In short, it is used to capture a rectangle and draw it to an image. Let us see how to use this method to capture the current screen.
How to capture the current screen using Windows Forms
The Graphics class exposes a method called CopyFromScreen(). According to MSDN, this method performs a bit-block transfer of the color data, corresponding to a rectangle of pixels, from the screen to the drawing surface of the Graphics. In short, it is used to capture a rectangle and draw it to an image. Let us see how to use this method to capture the current screen.
The signature of this method is as follows :
public void CopyFromScreen(
int sourceX,
int sourceY,
int destinationX,
int destinationY,
Size blockRegionSize)
where sourceX and sourceY are the x and y coordinate of the point at the upper-left corner of the ‘source’ rectangle. The destinationX and destinationY are the x and y coordinate of the point at the upper-left corner of the ‘destination’ rectangle.
In this example, we will be creating a bitmap equal to the height and width of the primary display. We then create a new Graphics from the specified bitmap. The Graphics.CopyFromScreen() is used to capture the screen and draw it in the bitmap. Once done, the image is saved to the desktop. Let us see some code.
Create a form and drop a button on it from the toolbar. Rename the button as btnCapture.
C#
private void btnCapture_Click(object sender, EventArgs e)
{
Graphics graph = null;
try
{
Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
graph = Graphics.FromImage(bmp);
graph.CopyFromScreen(0,0, 0, 0, bmp.Size);
SaveImage(bmp);
}
finally
{
graph.Dispose();
}
}
private void SaveImage(Bitmap b)
{
b.Save(@"C:\1.bmp");
}
VB.NET
Private Sub btnCapture_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim graph As Graphics = Nothing
Try
Dim bmp As Bitmap = New Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height)
graph = Graphics.FromImage(bmp)
graph.CopyFromScreen(0,0, 0, 0, bmp.Size)
SaveImage(bmp)
Finally
graph.Dispose()
End Try
End Sub
Private Sub SaveImage(ByVal b As Bitmap)
b.Save("C:\1.bmp")
End Sub
That was quiet easy right. You have built the ‘Print Screen’ functionality successfully using Windows Forms. I hope this article was useful and I thank you for viewing it.
If you liked the article, please subscribe to my RSS feed over here.
Give me a +1 if you think it was a good article. Thanks!