The Windows registry is an ideal place for storing position and size information for a form. Typically, you'll store information about each form in a separate key, perhaps using the class name of the form. These keys will be stored under an application-specific key.
To automate this process, it helps to create a dedicated class that saves and retrieves form settings. The FormSettingStore class shown in the following example fills this role. This class provides a SaveSettings method that accepts a form and writes its size and position information to the registry, as well as an ApplySettings method that accepts a form and applies the settings from the registry. The registry key path and the name of the form subkey are stored as class member variables.
using System;
using System.Windows.Forms;
using Microsoft.Win32;
public class FormSettingStore {
private string regPath;
private string formName;
private RegistryKey key;
public string RegistryPath {
get {return regPath;)
}
public string FormName {
get {return formName;}
}
public FormSettingStore(string registryPath, string formName) {
this.regPath = registryPath;
this.formName = formName;
// Create the key if it doesn't exist.
key = Registry.LocalMachine.CreateSubKey(registryPath + formName);
}
public void SaveSettings(System.Windows.Forms.Form form) {
key.SetValue("Height", form.Height);
key.SetValue("Width", form.Width);
key.SetValue("Left", form.Left);
key.SetValue("Top", form.Top);
}
public void ApplySettings(System.Windows.Forms.Form form) {
// If form settings are not available, the current form settings
// are used instead.
form.Height = (int)key.GetValue("Height", form.Height);
form.Width = (int)key.GetValue("Width", form.Width);
form.Left = (int)key.GetValue("Left", form.Left);
form.Top = (int)key.GetValue("Top", form.Top);
}
}
To use the FormSettingStore class, simply add the event-handling code shown here to any form. This code saves the form properties when the form closes and restores them when the form is loaded.
private FormSettingStore formSettings;
private void Form1_Load(object sender, System.EventArgs e) {
formSettings = new FormSettingStore(@"Software\MyApp\", this.Name);
formSettings.ApplySettings(this);
}
private void Form1_Closed(object sender, System.EventArgs e) {
formSettings.SaveSettings(this);
}
RSS Feed (xml)


No comments:
Post a Comment