How to Capture a Screen Using C#

Introduction

Here we will implement a Windows Forms application to capture a screen using C#.

It is a very short demo especially for beginners.

Procedure

Step 1: Create a new “Windows Forms application” in Visual Studio and name it as you choose (I here named it ScreenCaptureDemo).

Now a new form is generated.

Step 2: Now go to the toolbox and add a Button Control to the project also resize the window size.

The form will look like this:

Step 3: Add the following using directives:

using System.Drawing.Imaging;
using System.Drawing;
using System;

Step 4: Now navigate to the code file Form1.cs and the following code in the Button Event Handler that we added to our project. 

private void buttonCapture_Click(object sender, EventArgs e)
{
    //Creating a Method name CaptureMyScreen
    CaptureMyScreen();
} 
private void CaptureMyScreen()
{
}

Step 5: Now add the following code into the method that we created (CaptureMyScreen()):

private void CaptureMyScreen()
{
    try
    {
        //Creating a new Bitmap object
        Bitmap captureBitmap = new Bitmap(1024, 768, PixelFormat.Format32bppArgb);       
        //Bitmap captureBitmap = new Bitmap(int width, int height, PixelFormat);
        //Creating a Rectangle object which will  
        //capture our Current Screen
        Rectangle captureRectangle = Screen.AllScreens[0].Bounds;
        //Creating a New Graphics Object
        Graphics captureGraphics = Graphics.FromImage(captureBitmap);
        //Copying Image from The Screen
        captureGraphics.CopyFromScreen(captureRectangle.Left,captureRectangle.Top,0,0,captureRectangle.Size);
        //Saving the Image File (I am here Saving it in My E drive).
        captureBitmap.Save(@"E:\Capture.jpg",ImageFormat.Jpeg);
        //Displaying the Successfull Result
        MessageBox.Show("Screen Captured");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Step 6: Now compile it and run it.

You will get your captured screen.

That's all for this article. I am embedding the source file so that you can go through it.

Thank You.


Similar Articles