Friday, September 17, 2010

C# Tutorial: Capture Screen [Take Screenshots]

Here is the code

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

///////////////// Declarations ////////////////////////
ImageFormat img; Bitmap bt; Graphics screenShot;

///////////////////// Button1 /////////////////////////////
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    this.Hide();
    // This gives time to the Form to hide before it takes the screenshot. 500 miliseconds are enough.
    Thread.Sleep(500); 
    // Set the image to the size of the screen.
    bt = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
    // Creates the graphic object for the image (bt).    
    screenShot = Graphics.FromImage(bt);
    // Takes the screenshot.
    screenShot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, 

CopyPixelOperation.SourceCopy);
    switch (saveFileDialog1.FilterIndex)
    {
        case 0: img = ImageFormat.Bmp; break;
        case 1: img = ImageFormat.Png; break;
        case 2: img = ImageFormat.Jpeg; break;
    }
    // Saves the image.
    bt.Save(saveFileDialog1.FileName, img);
    // After the screenshot is taken the Form reappears.
    this.Show();
}

Or download the solution

4 comments:

  1. Change the download link for the solution please :) it is no longer valid.

    ReplyDelete
  2. Thanks for this,

    Can you write a tutorial on how to capture screen with dragging mouse area?

    ReplyDelete