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.
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);
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);
}
}
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