Tuesday, August 3, 2010

Save Window Position in Registry

This is how you could save a Window position in the Registry so that the Window position could be restored next time the Form loads.


Declare the following constant strings:

 public const string REGKEY = @"SOFTWARE\MyCompany\MyApp\"; 
public const string WINWIDTH = "windowWidth";
public const string WINHEIGHT = "windowHeight";

Then, create a key for your application in the Registry. 
Declare a RegistryKey variable:
private RegistryKey key;

Use the following method to obtain the key:

public RegistryKey GetKey(string RegKey)
{
            RegistryKey Key = Registry.CurrentUser.OpenSubKey(RegKey, true);
            if (Key == null)
            {
                Key = Registry.CurrentUser.CreateSubKey(RegKey);
            }
            return Key;
}

key =  GetKey(REGKEY);

Get window width and height:

int width = Form1.Size.Width;
int height = Form1.Size.Height;
Save window width and height in the registry and close the RegistryKey.


key.SetValue(WINWIDTH, width);
key.SetValue(WINHEIGHT, height);
key.Close(); 
When you load your form, read the values from the registry:
width = Convert.ToInt16 (key.GetValue(WINWIDTH));
height = Convert.ToInt16 (key.GetValue(WINHEIGHT));

Set the new window size:
Form1.Size = new Size(width, height);

No comments:

Post a Comment