Tuesday, December 8, 2009

Screenshots in C# Winforms

Here are a few C# methods to take screenshots of controls, or windows forms:


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ICanHasCode
{
    public static class ScreenshotHelper
    {
        ///
        /// returns null on error, or screenshot full path & filename on success
        ///
        ///

        ///
        public static string SaveScreenShot()
        {
            Bitmap bmpScreenshot;

            Graphics gfxScreenshot;

            bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
            gfxScreenshot = Graphics.FromImage(bmpScreenshot);
            gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);

            string fileName = System.Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\" + Guid.NewGuid() + ".jpg";
            bmpScreenshot.Save(fileName, ImageFormat.Jpeg);
            return fileName;
        }

        public static string SaveScreenShot(System.Windows.Forms.Form form)
        {
            Bitmap bmpScreenshot;

            Graphics gfxScreenshot;
            form.BringToFront();
            form.Refresh();
            Application.DoEvents();
            bmpScreenshot = new Bitmap(form.Bounds.Width, form.Bounds.Height, PixelFormat.Format32bppArgb);
            gfxScreenshot = Graphics.FromImage(bmpScreenshot);
            gfxScreenshot.CopyFromScreen(form.Bounds.X, form.Bounds.Y, 0, 0, form.Bounds.Size, CopyPixelOperation.SourceCopy);

            string fileName = System.Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\" + Guid.NewGuid() + ".jpg";
            bmpScreenshot.Save(fileName, ImageFormat.Jpeg);
            form.SendToBack();
            return fileName;

        }

        public static string SaveScreenShot(System.Windows.Forms.Control control)
        {
            Bitmap bmpScreenshot;

            Graphics gfxScreenshot;
            control.BringToFront();
            control.Refresh();
            Application.DoEvents();
            bmpScreenshot = new Bitmap(control.Bounds.Width, control.Bounds.Height, PixelFormat.Format32bppArgb);
            gfxScreenshot = Graphics.FromImage(bmpScreenshot);
            gfxScreenshot.CopyFromScreen(control.Bounds.X, control.Bounds.Y, 0, 0, control.Bounds.Size, CopyPixelOperation.SourceCopy);

            string fileName = System.Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\" + Guid.NewGuid() + ".jpg";
            bmpScreenshot.Save(fileName, ImageFormat.Jpeg);
            return fileName;

        }
    }
}

No comments:

Post a Comment

There was an error in this gadget