Tac*_*cit 4 c# savestate visual-studio-2010 winforms
我有一个小程序,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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果查看项目属性页,可以添加设置文件.
要使用代码中的设置,您可以执行以下操作:
Properties.Settings.Default.SettingName
Run Code Online (Sandbox Code Playgroud)
请记住,这些设置是本地的,需要在每台机器上指定
示例代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
以下是MSDN上设置类的链接 http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx
这对您来说可能/可能不容易.
首先创建一个类来保存你的状态:
public class MyFormState {
public string ButtonBackColor { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在,Form
使用此对象声明您的成员:
public partial class Form1 : Form {
MyFormState state = new MyFormState();
Run Code Online (Sandbox Code Playgroud)
在表单加载时,检查配置是否存在,然后加载它:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
表单关闭时..保存配置:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将成员添加到您的州类,并将它们写入config.xml文件.
归档时间: |
|
查看次数: |
14585 次 |
最近记录: |