BLOG.CSHARPHELPER.COM: Save an image of the computer's screen in a file in C#
Save an image of the computer's screen in a file in C#
The Graphics object's CopyFromScreen method copies some or all of the screen's image to the Graphics object. The follow GetScreenImage method uses CopyFromScreen to grab an image of the screen. The only tricky part is using Screen.PrimaryScreen.Bounds to get the screen's dimensions.
// Grab the screen's image. private Bitmap GetScreenImage() { // Make a bitmap to hold the result. Bitmap bm = new Bitmap( Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format24bppRgb);
// Copy the image into the bitmap. using (Graphics gr = Graphics.FromImage(bm)) { gr.CopyFromScreen( Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); }
// Return the result. return bm; }
(You might need to modify this code if you use multiple monitors. If you do, let me know how it works out.)
The main program is relatively simple.
// Let the user pick a file to hold the image. if (sfdScreenImage.ShowDialog()==DialogResult.OK) { // Get the screen's image. using (Bitmap bm = GetScreenImage()) { // Save the bitmap in the selected file. string filename = sfdScreenImage.FileName; FileInfo file_info = new FileInfo(filename); switch (file_info.Extension.ToLower()) { case ".bmp": bm.Save(filename, ImageFormat.Bmp); break; case ".gif": bm.Save(filename, ImageFormat.Gif); break; case ".jpg": case ".jpeg": bm.Save(filename, ImageFormat.Jpeg); break; case ".png": bm.Save(filename, ImageFormat.Png); break; default: MessageBox.Show("Unknown file type " + file_info.Extension, "Unknown Extension", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } } }
// Show this form again. this.Show(); }
The code hides the program's form (so it doesn't appear in the screen capture). It then displays a save file dialog to let the user select the output file. If the user selects a file, the program uses GetScreenImage to get the screen's image and saves it in a file of the appropriate type.
Comments