ali raza

C#, .Net , and my thoughts

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 = @”Software\App\”;
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)
and call the SetSize() method when the form is first opened:

private void MyForm_Load(object sender, System.EventArgs e)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: