简体   繁体   中英

How to save the state of a form?

I've built a Windows form application which contains some forms. I would like to create a button on a certain form which saves its state.

For example, if I have a textbox in which a user typed "Hello" and pressed the save button, when he goes back to this form, the textbox would still say "Hello". I want it to happen only in the same execution of the program, which means when the program closes and reopens, the textbox wouldn't say "Hello" anymore (which is why Settings don't fit my need I believe, because they keep the changes between executions).

Since you only want the form to retain its state while the application is running, the solution is very simple: never close the form, just hide it. When you're ready to display it again, show it. It will re-appear on the screen, everything exactly as it was left. (Unless, of course, you loop through the controls and reset their properties.)

In the simplest case, you accomplish this by substituting calls to this.Close with this.Hide . But it is likely more complicated than that, since the user can close your form with the big red X. To ensure all attempts to close the form are stealthily rerouted as requests to hide the form requires some minor finesse:

private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        e.Cancel = true;  // cancel the request to close
        this.Hide();      // hide the form instead
    }
}

Note that this code checks the close reason and ensures that it's a user-initiated close request. This is very important. If you omit this part, you can't close the form programmatically, either!

将数据存储在静态变量中,它们将一直存在,直到您关闭程序。

static string textboxText = textbox1.text;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM