Easily save and restore a form’s settings in the Registry in C#

example

This example shows how you can easily save and restore all of a form’s settings and the values of its controls in the Registry in C#.

The example Save and restore program settings in C# saves and restores a form’s size and position in the program’s settings. This example saves and restores the form’s size, position, and window state (normal, minimized, or maximized). It also saves the values in all of the form’s controls. (This example handles TextBoxes, ComboBoxes, RadioButtons, NumericUpDown controls, and scroll bars. You can use similar techniques to make it handle other controls if you like.)

The code is pretty long so I’m only going to show some of it here. Download the example to see the rest.

Saving Values

The program saves the values in the system Registry. The following SaveSetting method saves a setting’s value in the Registry.

// Save a value.
public static void SaveSetting(string app_name,
    string name, object value)
{
    RegistryKey reg_key =
        Registry.CurrentUser.OpenSubKey("Software", true);
    RegistryKey sub_key = reg_key.CreateSubKey(app_name);
    sub_key.SetValue(name, value);
}

This code uses the Microsoft.Win32.RegistryKey class to make saving settings in the Registry easy. It takes a name and value as parameters. It uses the Registry.CurrentUser.OpenSubKey method to open the key for the Software Registry hive. It makes a subkey named after the application, and then creates a value inside that subkey with the desired name and value.

The following SaveAllSettings method uses SaveSetting to save the form’s basic information.

// Save all of the form's settings.
public static void SaveAllSettings(string app_name, Form frm)
{
    // Save form settings.
    SaveSetting(app_name, "FormWindowState", (int)frm.WindowState);
    if (frm.WindowState == FormWindowState.Normal)
    {
        // Save current bounds.
        SaveSetting(app_name, "FormLeft", frm.Left);
        SaveSetting(app_name, "FormTop", frm.Top);
        SaveSetting(app_name, "FormWidth", frm.Width);
        SaveSetting(app_name, "FormHeight", frm.Height);
    }
    else
    {
        // Save bounds when we're restored.
        SaveSetting(app_name, "FormLeft", frm.RestoreBounds.Left);
        SaveSetting(app_name, "FormTop", frm.RestoreBounds.Top);
        SaveSetting(app_name, "FormWidth",
            frm.RestoreBounds.Width);
        SaveSetting(app_name, "FormHeight",
            frm.RestoreBounds.Height);
    }

    // Save the controls' values.
    SaveChildSettings(app_name, frm);
}

This code first saves the form’s WindowState. Then, if the form is in its normal state, the method saves its current size and position. If the form is minimized or maximized, the method saves the form’s restored bounds–the size and position it has when in the normal state. The method finishes by calling SaveChildSettings to save the values in the form’s controls.

The following SaveChildSettings method saves TextBox.Text values, ComboBox.Checked values, and so forth.

// Save all child control settings.
public static void SaveChildSettings(string app_name,
    Control parent)
{
    foreach (Control child in parent.Controls)
    {
        // Save the child's value.
        switch (child.GetType().Name)
        {
            case "TextBox":
            case "ListBox":
            case "ComboBox":
                SaveSetting(app_name, child.Name, child.Text);
                break;
            case "CheckBox":
                CheckBox chk = child as CheckBox;
                SaveSetting(app_name, child.Name,
                    chk.Checked.ToString());
                break;
            case "RadioButton":
                RadioButton rad = child as RadioButton;
                SaveSetting(app_name, child.Name,
                    rad.Checked.ToString());
                break;
            case "VScrollBar":
                VScrollBar vscr = child as VScrollBar;
                SaveSetting(app_name, child.Name, vscr.Value);
                break;
            case "HScrollBar":
                HScrollBar hscr = child as HScrollBar;
                SaveSetting(app_name, child.Name, hscr.Value);
                break;
            case "NumericUpDown":
                NumericUpDown nud = child as NumericUpDown;
                SaveSetting(app_name, child.Name, nud.Value);
                break;
            // Add other control types here.
        }

        // Recursively save the child's children.
        SaveChildSettings(app_name, child);
    }
}

This method takes as a parameter a parent control and loops through that control’s child controls. The code uses a switch statement to see what kind of control each child is and uses SaveSetting to save the control’s appropriate values. It then recursively calls itself to save the values of the child’s children.

Loading Values

The code that loads values is sort of similar to the code that saves values. It just performs reverse operations. Because the code is similar, I’ll only describe it here without showing it.

The GetSetting method uses the Microsoft.Win32.RegistryKey class to make restoring settings from the Registry easy. It takes a name and default value as parameters. It looks up the name and returns the saved value if it’s in the Registry or the default value if it isn’t.

The LoadAllSettings method simply retrieves the saved form size and position and uses them to arrange the form. It also sets the form’s WindowState. It finishes by calling LoadChildSettings to load the controls’ saved values.

The LoadChildSettings method loops through a parent control’s children. It uses GetSetting to restore the child’s saved values and then recursively calls itself to load the values in the control’s children.

Using the Methods

Having written these methods, using them is easy. I put them in the RegistryTools class to make them easy to move into new projects. The program simply calls the static LoadAllSettings and SaveAllSettings methods in the form’s Load and FormClosing event handlers. The following code uses the application’s product name to identify the section in the Regsitry where the values should be stored.

// Load the saved settings.
private void Form1_Load(object sender, EventArgs e)
{
    RegistryTools.LoadAllSettings(Application.ProductName, this);
}

private void Form1_FormClosing(object sender,
    FormClosingEventArgs e)
{
    RegistryTools.SaveAllSettings(Application.ProductName, this);
}


Download Example   Follow me on Twitter   RSS feed




This entry was posted in forms, programs, registry and tagged , , , , , , , , , , , . Bookmark the permalink.

7 Responses to Easily save and restore a form’s settings in the Registry in C#

  1. That was an awesome article. I came by this article and found it extraordinarily helpful.

  2. Mahmood Koura says:

    Hello sir,

    this is so informative i`ve been searching for something like that for a long time i`m new with registry … and was coding a sticky note for my brother with a reminder and that is done but i want to make it when the reminder is set to another date (like tomorrow) and he shut down his computer it saves the date, time and note which is done by this tutorial … and when he opens the computer it show up the note at the date and time .. hope you understood what i want 🙂

    thanks again ..

  3. Rod Stephens says:

    You should be able to do that. Save each message with a date on which that message should be displayed. Then when the program starts, it can load the current day’s message.

    That approach would work but I might display all of the messages instead of just showing today’s message. That way you can get a hint of what is coming over the next few days. (I may put together an example in the next few days.)

    In fact, you could build a whole calendar application. You might want to look at some of the calendar programs that are out there to see what features they provide. (Or you could just buy one of them or get a free one 😉

  4. Mahmood Koura says:

    yeah well i was trying to make something like a calender but without a calender itself … thanks anyways i`ll try that 🙂

  5. Rod Stephens says:

    It sort of depends on how many features you want. You can definitely do the post-it style popup on the day a message is due. Or you could build a full-blown calendar that would have a lot more features but be a lot more work.

    Maybe you should start with the first idea and see how it goes. Just store both the date and message so the program can check the date when it starts.

  6. Pingback: Use a TreeView to display property pages in C#

  7. Pingback: Add ComboBox choices at runtime in C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *