65.9K
CodeProject is changing. Read more.
Home

Save WinForm Snapshot Images

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.60/5 (5 votes)

Aug 3, 2018

CPOL
viewsIcon

16319

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

  • 2nd August, 2018: Version 1.0