上面红色框中两个文件,若不存在或内容不规范,需要修改如下:
Settings.cs:
namespace IfoxDemo.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.9.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default => defaultInstance;
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public string TB1 {
get => ((string)(this["TB1"]));
set => this["TB1"] = value;
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public string TB2 {
get => ((string)(this["TB2"]));
set => this["TB2"] = value;
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public string TB3 {
get => ((string)(this["TB3"]));
set => this["TB3"] = value;
}
}
}
Settings.settings:
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings"
CurrentProfile="(Default)"
GeneratedClassNamespace="IfoxDemo.Properties"
GeneratedClassName="Settings">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings>
<Setting Name="TB1" Type="System.String" Scope="User">
<Value Profile="(Default)" />
</Setting>
<Setting Name="TB2" Type="System.String" Scope="User">
<Value Profile="(Default)" />
</Setting>
<Setting Name="TB3" Type="System.String" Scope="User">
<Value Profile="(Default)" />
</Setting>
</Settings>
</SettingsFile>
在窗体文件中加入以下代码:
public Form1()
{
InitializeComponent();
// 窗体加载时触发(也可以写在 Form1_Load 事件中)
this.Load += (sender, e) =>
{
// 从用户设置中读取上次保存的值(如果没有则为空)
textBox1.Text = Properties.Settings.Default.TB1; // 对应 TB1
textBox2.Text = Properties.Settings.Default.TB2; // 对应 TB2
textBox3.Text = Properties.Settings.Default.TB3; // 对应 TB3
// 窗体关闭时保存当前值
this.FormClosing += (sender, e) =>
{
Properties.Settings.Default.TB1 = textBox1.Text;
Properties.Settings.Default.TB2 = textBox2.Text;
Properties.Settings.Default.TB3 = textBox3.Text;
Properties.Settings.Default.Save(); // 必须调用 Save()
};
};
}
窗体项目最好不要把doc ed db等做成静态函数,因为用户可能换个dwg文件继续执行窗体,这时候代码中的doc还是老dwg,容易造成bug、致命错误、闪退等。