在退出时保存应用程序的所有更改

时间:2014-04-07 14:04:57

标签: c# winforms save savechanges

我在C#中有一个Windows窗体应用程序,我可以在运行时添加多个控件。关闭应用程序后保存所有更改的最佳/最简单方法是什么?基本上如果我在运行时添加两个按钮,在我关闭应用程序并再次打开它之后,我应该在那里使用所有功能和设置的拖动按钮。

您能否推荐一些可能的解决方案来实现这一目标?

2 个答案:

答案 0 :(得分:1)

您可以保存一些描述应用程序上下文的XML文件

答案 1 :(得分:1)

实际上,如果你想在运行时向你的表单添加未知数量的控件,然后在下次运行时再次重新创建它们,实际上你可以。

将对象写入硬盘并再次加载它们的方法之一。你可以使用序列化来做到这一点。遗憾的是,您无法序列化控件对象,但您可以创建一些类,其中包含{type,location,size,forecolor,backcolor}等常见属性。

在exit创建一个列表并创建一个对象来保存每个控件属性,然后将该对象添加到列表中,最后序列化整个列表。

检查这些链接以了解有关序列化的更多信息 What is [Serializable] and when should I use it?

http://www.dotnetperls.com/serialize-list

我也可以为您提供这段代码,帮助您理解

    [Serializable]//class to hold the common properties
    public class Saver
    {
        public Saver() { }
        public Point Location { get; set; }
        public Type Type { get; set; }
        public Size Size { get; set; }
        public string Text { get; set; }
        //add properties as you like but maker sure they are serializable too
    }

以下两个保存和加载数据的功能

    public void SaveControls(List<Control> conts, Stream stream)
    {
        BinaryFormatter bf = new BinaryFormatter();

        List<Saver> sv = new List<Saver>();

        foreach (var item in conts)
        {
            //save the values to the saver object
            Saver saver = new Saver();
            saver.Type = item.GetType();
            saver.Location = item.Location;
            saver.Size = item.Size;
            saver.Text = item.Text;

            sv.Add(saver);
        }

        bf.Serialize(stream, sv);//serialize the list
    }

这是第二个

    public List<Control> LoadControls(Stream stream)
    {
        BinaryFormatter bf = new BinaryFormatter();

        List<Saver> sv =(List<Saver>) bf.Deserialize(stream);

        List<Control> conts = new List<Control>();

        foreach (var item in sv)
        {
            //create an object at run-time using it's type
            Control c = (Control)Activator.CreateInstance(item.Type);

            //reload the saver values into the control object
            c.Location = item.Location;
            c.Size = item.Size;
            c.Text = item.Text;

            conts.Add(c);
        }

        return conts;

    }
相关问题