A very common requirement for Windows Forms applications is the ability to 'remember' the location and size of forms when they are closed, so that the next time they are shown, they can be restored to the former position. The Application Settings feature is .NET 2.0 makes it simple to do this, but unfortunately, it is a little hard to get it 'just right'. This question is asked frequently on internal and external Microsoft forums, so I thought it warranted a blog post.
Now, the Windows Forms designer in Visual Studio 2005 provides a simple UI to data bind properties on controls to application settings. So the first thing that might occur to you is to simply bind the Form's Location and Size properties to settings, add a line of code to save the settings class, and that's it! Unfortunately, this is not the best option for a few reasons:
The good news is that this is very easy to do with a few lines of code:
private void Form1_FormClosing(object sender, FormClosingEventArgs e){ Properties.Settings.Default.MyState = this.WindowState; if (this.WindowState == FormWindowState.Normal) { Properties.Settings.Default.MySize = this.Size; Properties.Settings.Default.MyLoc = this.Location; } else { Properties.Settings.Default.MySize = this.RestoreBounds.Size; Properties.Settings.Default.MyLoc = this.RestoreBounds.Location; } Properties.Settings.Default.Save(); } private void Form1_Load(object sender, EventArgs e) { this.Size = Properties.Settings.Default.MySize; this.Location = Properties.Settings.Default.MyLoc; this.WindowState = Properties.Settings.Default.MyState; }
private void Form1_FormClosing(object sender, FormClosingEventArgs e){ Properties.Settings.Default.MyState = this.WindowState;
if (this.WindowState == FormWindowState.Normal) { Properties.Settings.Default.MySize = this.Size; Properties.Settings.Default.MyLoc = this.Location; } else { Properties.Settings.Default.MySize = this.RestoreBounds.Size; Properties.Settings.Default.MyLoc = this.RestoreBounds.Location; } Properties.Settings.Default.Save();
if (this.WindowState == FormWindowState.Normal)
{
Properties.Settings.Default.MySize = this.Size;
Properties.Settings.Default.MyLoc = this.Location;
}
else
Properties.Settings.Default.MySize = this.RestoreBounds.Size;
Properties.Settings.Default.MyLoc = this.RestoreBounds.Location;
Properties.Settings.Default.Save();
private void Form1_Load(object sender, EventArgs e)
this.Size = Properties.Settings.Default.MySize; this.Location = Properties.Settings.Default.MyLoc; this.WindowState = Properties.Settings.Default.MyState;
this.Size = Properties.Settings.Default.MySize;
this.Location = Properties.Settings.Default.MyLoc;
this.WindowState = Properties.Settings.Default.MyState;
By the way, speaking of Windows Forms 2.0, there is a lot of great new content on the WindowsForms.net site. Jessica has been actively blogging on interesting Windows Forms topics too.