≡ Menu




Saving and Restoring Form Location

A common requirement for a form is to remember its last location. Usually, this information
is stored in the registry. The code that follows shows a helper class that automatically stores
information about a form’s size and position using a key based on the name of a form.
public class FormPositionHelper
{
public static string RegPath = @”SoftwareApp”;
public static void SaveSize(System.Windows.Forms.Form frm)
{
// Create or retrieve a reference to a key where the settings will be stored.
RegistryKey key;
key = Registry.LocalMachine.CreateSubKey(RegPath + frm.Name);
key.SetValue(“Height”, frm.Height);
key.SetValue(“Width”, frm.Width);
key.SetValue(“Left”, frm.Left);
key.SetValue(“Top”, frm.Top);
}

public static void SetSize(System.Windows.Forms.Form frm)
{
RegistryKey key;
key = Registry.LocalMachine.OpenSubKey(RegPath + frm.Name);
if (key != null)
{
frm.Height = (int)key.GetValue(“Height”);
frm.Width = (int)key.GetValue(“Width”);
frm.Left = (int)key.GetValue(“Left”;
frm.Top = (int)key.GetValue(“Top”);
}
}
}
To use this class in a form, you call the SaveSize() method when the form is closing:

private void MyForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
FormPositionHelper.SaveSize(this);
}
and call the SetSize() method when the form is first opened:

private void MyForm_Load(object sender, System.EventArgs e)
{
FormPositionHelper.SetSize(this);
}

{ 0 comments… add one }

Leave a Comment