简体   繁体   中英

Automatically save settings on exit C#

In VB.NET there is an option to "Automagically save settings on exit" is there an equivalent option in C# or does one need to write the following code?"

private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
    Properties.Settings.Default.Save();
}

You could use ApplicationExit instead.

Application.ApplicationExit += new EventHandler(Application_ApplicationExit);

void Application_ApplicationExit(object sender, EventArgs e)
{
    Settings.Default.Save();
}

Alternatively, you could also save on every change:

Settings.Default.PropertyChanged += new PropertyChangedEventHandler(Default_PropertyChanged);

void Default_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    Settings.Default.Save();
}

Warning: If you use the second approach, please consider the comments by @Hans Passant

You can do it this way, too. If you're using Windows Forms, bring up the Events tab from within the Properties Pane in Design-View for the Form you'd like to use, and scroll down till you see the Closing Event, then double-click it.

Next, just add the code shown below.

private void Form1_Closing(object sender, EventArgs e)
{
    Properties.Settings.Default.Save();
}

Yup, that's it. I prefer to handle save, reset, reload at the form level because the settings are shared across the app. Calling .Reset() on FormCancel does the right thing for the user, as well as calling .Save() when the form closes. If the app crashes after that point, the settings are preserved. I think that saving on AppStart/Exit doesn't do the right thing for the user at the right time.

Settings.Default.Save();

Other interesting methods:

.Upgrade();

.Reset();

.Reload();

根据这篇文章,它完全一样

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