如何使VS 2019程序记住以前的实例首选项?

问题描述

我目前正在制作文本编辑器,并且创建了一个明暗主题,可以通过按一个按钮进行更改。主题为浅色,但我希望它记住我选择的最后一个主题。因此,如果我选择了深色并关闭了它,则下次在启用该主题的情况下打开它。

我还想知道如何使它记住一般的东西。

解决方法

尝试查看Properties.Settings

//Sets a string created in the setting
Properties.Settings.Default.FirstString = "Hello World";
//saves the property,this setting will then persist after closing the aplication.
Properties.Settings.Default.Save();
,

我们可以通过Project -> Project Properties… -> Settings将“主题”保存到“设置”中。

并创建一个名为“主题”的设置,将其值设置为“浅”。

enter image description here

然后我们可以通过以下代码访问“主题”。

private void btnChangeTheme_Click(object sender,EventArgs e)
{
    if(Properties.Settings.Default.Theme == "Light")
    {
        Properties.Settings.Default.Theme = "Dark";
    }
    else
    {
        Properties.Settings.Default.Theme = "Light";
    }

    string theme = Properties.Settings.Default.Theme;
    // if(theme == "Light"){...}else{...}
    // here is the code that modify theme
    // ...
    Properties.Settings.Default.Save();
}

private void Form1_Load(object sender,EventArgs e)
{
    // load theme
    string theme = Properties.Settings.Default.Theme;
    // if(theme == "Light"){...}else{...}
    // here is the code that modify theme
    // ...
}