Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Save WinForm snapshot images

0.00/5 (No votes)
2 Aug 2018 1  
Simple C# methods for saving snapshot images of a WinForm to the desktop.

Introduction

As a tip for users/developers of visualization desktop applications, I’d like to call attention to two methods which I have found very useful. One of these simply saves the entire Form as a .png file on the desktop. Getting that to work right seemed tricky to me but very worthwhile. The other method just checks to see if a filename already exists and, if so, adds an incremented copy number to the pathname. These two methods make saving snapshots of a form simple and quick.

 

Using the code

Typically, I place a "Save Image" button near a corner of my Form using the designer and set Save_Image_Button_Click() as the Click event for that button.

 

/// <summary>
/// Save the Form Image to the Desktop
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Save_Image_Button_Click(object sender, EventArgs e)
{
    string MyDesktopPath = Environment.GetFolderPath(
        System.Environment.SpecialFolder.DesktopDirectory) + "\\";

    using (Bitmap bmpScreenshot = new Bitmap(Bounds.Width, Bounds.Height, PixelFormat.Format32bppArgb))
    {
        Rectangle rect = new Rectangle(0, 0, this.Bounds.Width, this.Bounds.Height);
        this.DrawToBitmap(bmpScreenshot, rect);

        // Build the filename
        string myFilepath = SaveFileNameCheck(MyDesktopPath, "MyFormName.png");
        if (myFilepath == "")
        {
            Console.WriteLine("Form image save FAILED!");
            return;
        }
        bmpScreenshot.Save(myFilepath, ImageFormat.Png);
        Console.WriteLine("Form image saved: {0}", myFilepath);
    }
}

/// <summary>
/// If filename exists, add or increment a # before any extension and check again
/// </summary>
/// <param name="path">Directory path to file location</param>
/// <param name="filename">Filename (to be incremented if existent)</param>
/// <returns>Complete pathname for file, possibly incremented, with original extension, if any</returns>
string SaveFileNameCheck(string path, string filename)
{
    if (!Directory.Exists(path)) return "";
    string filenamewoext = Path.GetFileNameWithoutExtension(filename);
    string extension = Path.GetExtension(filename);
    int count = 1;
    while (File.Exists(path + filename))
    {
        filename = filenamewoext + "(" + count.ToString() + ")" + extension;
        count++;
    }
    return path + filename;
}

 

History

August 2, 2018: version 1.0

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here