gomasch Development Notes

Montag, Januar 15, 2007

.Net Application Settings

keywords: .net application settings windows forms

it's not new at all but I want to have this somewhere:

/// <summary> /// purpose: helper class to save form size+location with .Net 2.0 application settings /// /// usage: /// 1. create two settings values e.g. /// -named "Size" of type "System.Drawing.Size" and set a default value /// -named "Location" of type "System.Drawing.Point" and set a default value /// 2. call ctor: /// new SaveFormSizeInSettings(this, "Size", "Location" MyNamespace.Properties.Settings.Default) /// BEFORE InitializeComponent()!!!! /// 3. call MyNamespace.Properties.Settings.Default.Save() in form_Closing /// </summary> public class SaveFormSizeInSettings { private Form form; private System.Configuration.ApplicationSettingsBase settings; private string sizeValueName; private string locationValueName; /// <summary> /// ctor /// </summary> /// <param name="form"></param> /// <param name="sizeValueName"></param> /// <param name="locationValueName"></param> /// <param name="settings"></param> public SaveFormSizeInSettings(Form form, string sizeValueName, string locationValueName, System.Configuration.ApplicationSettingsBase settings) { this.form = form; this.settings = settings; this.sizeValueName = sizeValueName; this.locationValueName = locationValueName; form.FormClosing += new FormClosingEventHandler(form_FormClosing); form.Load += new EventHandler(form_Load); } void form_Load(object sender, EventArgs e) { if ((null == settings[sizeValueName]) || (null == settings[locationValueName])) { // size or location not yet in settings return; } Size savedSize = (System.Drawing.Size)settings[sizeValueName]; Point savedLocation = (System.Drawing.Point)settings[locationValueName]; if (Screen.FromControl(form).Bounds.Contains(new Rectangle(savedLocation, savedSize))) { // fits into current screen form.Size = savedSize; form.Location = savedLocation; } } void form_FormClosing(object sender, FormClosingEventArgs e) { //size if (form.WindowState == FormWindowState.Normal) { settings[sizeValueName] = form.Size; } else { settings[sizeValueName] = form.RestoreBounds.Size; } // location settings[locationValueName] = form.Location; } }
martin schmidt 14:05 | 0 comments |