保存表单状态,然后以相同状态重新打开它
我有一个winforms
的小程序,有3个按钮。 到目前为止,该程序允许用户通过单击相应的按钮来更改另一个按钮的颜色,而第三个按钮还没有执行任何操作。 我想要做的是让用户保存对表单所做的更改(保存表单状态)。 因此,当重新打开表单时,它将以保存的相同状态打开。
我希望我清楚自己所追求的是什么
以下是表单的可视化:
如果有任何帮助,我到目前为止的代码:
public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { btnToColor.Text = ""; } int c = 0; private void btnColorSwap_Click(object sender, EventArgs e) { if (c == 0) { btnToColor.BackColor = Color.Yellow; c++; } else if (c == 1) { btnToColor.BackColor = Color.YellowGreen; c++; } else if (c == 2) { btnToColor.BackColor = Color.LimeGreen; c = 0; } } }
这对您来说可能/可能不容易。
首先创建一个类来保存你的状态:
public class MyFormState { public string ButtonBackColor { get; set; } }
现在,使用此对象声明Form
的成员:
public partial class Form1 : Form { MyFormState state = new MyFormState();
在表单加载时,检查配置是否存在,然后加载它:
private void Form1_Load(object sender, EventArgs e) { if (File.Exists("config.xml")) { loadConfig(); } button1.BackColor = System.Drawing.ColorTranslator.FromHtml(state.ButtonBackColor); } private void loadConfig() { XmlSerializer ser = new XmlSerializer(typeof(MyFormState)); using (FileStream fs = File.OpenRead("config.xml")) { state = (MyFormState)ser.Deserialize(fs); } }
表单关闭时..保存配置:
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { writeConfig(); } private void writeConfig() { using (StreamWriter sw = new StreamWriter("config.xml")) { state.ButtonBackColor = System.Drawing.ColorTranslator.ToHtml(button1.BackColor); XmlSerializer ser = new XmlSerializer(typeof(MyFormState)); ser.Serialize(sw, state); } }
然后,您可以将成员添加到您的州类,并将它们写入config.xml文件。
如果查看项目属性页,可以添加设置文件。
要使用代码中的设置,您可以执行以下操作:
Properties.Settings.Default.SettingName
请记住,这些设置是本地的,需要在每台机器上指定
示例代码:
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { Properties.Settings.Default.btn1 = button1.UseVisualStyleBackColor ? Color.Transparent : button1.BackColor; Properties.Settings.Default.btn2 = button1.UseVisualStyleBackColor ? Color.Transparent : button2.BackColor; Properties.Settings.Default.btn3 = button1.UseVisualStyleBackColor ? Color.Transparent : button3.BackColor; } private void Form1_Load(object sender, EventArgs e) { if (Properties.Settings.Default.btn1 != Color.Transparent) button1.BackColor = Properties.Settings.Default.btn1; if (Properties.Settings.Default.btn2 != Color.Transparent) button1.BackColor = Properties.Settings.Default.btn2; if (Properties.Settings.Default.btn3 != Color.Transparent) button1.BackColor = Properties.Settings.Default.btn3; }
这是MSDN上的设置类的链接http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx
属性页
通常当它来存储用户界面设置时,标准方法是使用XML文件来保存或加载我做的这个例子,用xml保存用户界面组件希望它有用
https://www.dropbox.com/s/1j1qbe7udqxizr6/4.XMLConfigurationEditor.rar?dl=0