Friday, February 29, 2008 5:27 PM
Download Source
The other day, I built a quick demo app using WinForms. It had been a while, and I couldn’t remember how to save the form’s current settings for the next session. Fairly old school, but I thought that it was pretty nifty anyway.
To demonstate, I built this little sample app:

When you close the form by clicking the Exit button, or by clicking the X in on the title bar, this application will save whatever was typed in the three text boxes. When you open the application the next time those text values will still be there. My demo uses the text in text boxes, but this could apply to anything: window position, background color, or some custom object.
Inside the Solution Explorer for my WinForm project, you simply have to expand the “Properties” folder, and double-click the default settings file.

If that file does not exist, create it by going to the project properties and choosing the “Settings” tab.
This will bring up the settings editor dialog.

Type the name of your settings, their data types, and any default values. The default values will be used if the settings have never been used (i.e., when the application starts for the first time). The settings file will be compiled into a type-safe class that you can use to retrieve and save these settings.
Add this function to your code behind, and call it from within the Form_Load event handler:
33
34 private void ApplySettings()
35 {
36 aInput.Text = Properties.Settings.Default.A;
37 bInput.Text = Properties.Settings.Default.B;
38 cInput.Text = Properties.Settings.Default.C;
39 }
40
The code above uses the “Default” instance of the Settings class to simply transfer the setting values into the text boxes.
Add the following function, and call it from your Form_Closing event handler:
28
29 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
30 {
31 SaveSettings();
32 }
33
Whenever the form closes the settings are assigned the values from the text boxes. The save method persists the information for the next session.