吴佳鑫的个人专栏

当日事当日毕,没有任何借口

导航

对象序列化(六):应用实例->程序退出时保存状态

应用序列化技术的一个典型开发场景就是保存应用程序的当前状态,它允许用户暂时中断当前的工作,关闭程序退出,下次重新启动程序时自动恢复上次的工作状态。

 

示例:

保存窗体颜色和位置的对象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace SaveFormStatus
{
[Serializable]
public class FormStatus
{
public Color BackgroundColor { get; set; }
public int Left { get; set; }
public int Top { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
}


主程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace SaveFormStatus
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
LoadStatus();
}

private void btnChooseColor_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
BackColor = colorDialog1.Color;
}
}

private FormStatus status = null;
private void SaveStatus()
{
status=new FormStatus();
status.BackgroundColor=this.BackColor;
status.Left=this.Left;
status.Top=this.Top;
status.Width=this.Width;
status.Height = this.Height;

using(FileStream fs=new FileStream("FormStatus.cfg",FileMode.Create))
{

IFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, status);

}
}

private void LoadStatus()
{
try
{
if (File.Exists("FormStatus.cfg"))
{

using (FileStream fs = new FileStream("FormStatus.cfg", FileMode.Open))
{
IFormatter formatter = new BinaryFormatter();
status = formatter.Deserialize(fs) as FormStatus;
if (status != null)
{
this.BackColor = status.BackgroundColor;
this.Left = status.Left;
this.Top = status.Top;
this.Width = status.Width;
this.Height = status.Height;

}
}
}

}
catch (Exception ex)
{

MessageBox.Show(ex.Message);
}

}

private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
SaveStatus();
}
}
}

 

posted on 2012-02-14 23:54  _eagle  阅读(440)  评论(0编辑  收藏  举报