C# WinForms 如何实现程序关闭后保存窗口、Margin、CheckBox、TextBox状态
WinForms 窗体状态重启自动还原实现代码
我们通过WinForms内置的用户范围配置机制实现状态持久化,覆盖需求要求的窗口大小、Margin属性、CheckBox选中值、TextBox输入内容自动还原,无需引入额外第三方组件。
前置配置
在项目属性的「设置」标签页中,添加以下用户范围的配置项(类型与对应值完全匹配):
FormWidth:int 类型,存储窗体宽度FormHeight:int 类型,存储窗体高度Form1Margin:System.Windows.Forms.Padding 类型,存储窗体Margin属性值CheckBox1Checked:bool 类型,存储第一个CheckBox的选中状态CheckBox2Checked:bool 类型,存储第二个CheckBox的选中状态TextBox1Content:string 类型,存储TextBox已输入的文本内容
修改后的完整窗体代码
using System; using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // 程序启动时读取已保存的配置,还原所有目标状态 try { // 还原窗口大小 if (Properties.Settings.Default.FormWidth > 0 && Properties.Settings.Default.FormHeight > 0) { this.Width = Properties.Settings.Default.FormWidth; this.Height = Properties.Settings.Default.FormHeight; } // 还原窗体Margin属性 this.Margin = Properties.Settings.Default.Form1Margin; // 还原两个CheckBox的选中值 checkBox1.Checked = Properties.Settings.Default.CheckBox1Checked; checkBox2.Checked = Properties.Settings.Default.CheckBox2Checked; // 还原TextBox内已输入的内容 textBox1.Text = Properties.Settings.Default.TextBox1Content; } catch { // 首次运行无历史配置时,静默跳过还原流程,不阻塞程序启动 } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // 程序关闭时把当前所有目标状态写入配置并持久化 Properties.Settings.Default.FormWidth = this.Width; Properties.Settings.Default.FormHeight = this.Height; Properties.Settings.Default.Form1Margin = this.Margin; Properties.Settings.Default.CheckBox1Checked = checkBox1.Checked; Properties.Settings.Default.CheckBox2Checked = checkBox2.Checked; Properties.Settings.Default.TextBox1Content = textBox1.Text; // 触发配置写入到本地用户配置文件 Properties.Settings.Default.Save(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void checkBox1_CheckedChanged(object sender, EventArgs e) { } private void checkBox2_CheckedChanged(object sender, EventArgs e) { } } }
注意事项
Form1_FormClosing事件需要在窗体设计器的事件面板中绑定到窗体的FormClosing事件,否则关闭时的状态保存逻辑不会触发。该实现同时兼容.NET Framework、.NET Core/.NET 5+ 版本的WinForms项目,无需额外修改代码。
内容的提问来源于stack exchange,提问作者M K
相关产品推荐
相关产品推荐

