Saving the form state then opening it back up in the same state

Tacit picture Tacit · Jan 31, 2013 · Viewed 17.1k times · Source

I have a small program in winforms that holds 3 buttons. Thus far the program lets the user change a the color of another button by clicking the corresponding button While the third button does not do anything yet. What I want to do is to let the user save changes made to the form (save the form state). So when the form is reopened it opens in that same state as saved.

I hope I am being clear about what I am after

Here is a visualization of the form:

enter image description here

The code that i have so far if any help:

public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            btnToColor.Text = "";
        }

        int c = 0;
        private void btnColorSwap_Click(object sender, EventArgs e)
        {
            if (c == 0)
            {
                btnToColor.BackColor = Color.Yellow;
                c++;

            }

            else if (c == 1)
            {
                btnToColor.BackColor = Color.YellowGreen;

                c++;
            }

            else if (c == 2)
            {
                btnToColor.BackColor = Color.LimeGreen;

                c = 0;
            }

        }
    }

Answer

Parimal Raj picture Parimal Raj · Jan 31, 2013

If you have a look in the project property pages you can add a settings file.

To use the settings in code you would do something like:

Properties.Settings.Default.SettingName

Do bare in mind though that these settings are local and would need to be specified on each machine

Sample Code :

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        Properties.Settings.Default.btn1 = button1.UseVisualStyleBackColor ? Color.Transparent : button1.BackColor;
        Properties.Settings.Default.btn2 = button1.UseVisualStyleBackColor ? Color.Transparent : button2.BackColor;
        Properties.Settings.Default.btn3 = button1.UseVisualStyleBackColor ? Color.Transparent : button3.BackColor;
    }

    private void Form1_Load(object sender, EventArgs e)
    {

        if (Properties.Settings.Default.btn1 != Color.Transparent) button1.BackColor = Properties.Settings.Default.btn1;
        if (Properties.Settings.Default.btn2 != Color.Transparent) button1.BackColor = Properties.Settings.Default.btn2;
        if (Properties.Settings.Default.btn3 != Color.Transparent) button1.BackColor = Properties.Settings.Default.btn3;
    }

Here is a link to the settings class on MSDN http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx


PropertyPages

Property Setting Page