Monday, January 24, 2011

Code and Example of FormSerializer utility class.

Scenario

You are writing a windows forms application and you want a simple way to save the location (and possibly other properties) of your WinForms.

Code for FormSerializer

using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace EomApp1.UI
{
    public class FormSerializer
    {
        public static void Serialize(Form f, string path)
        {
            XmlSerializer xs = new XmlSerializer(typeof(FormProps));
            using (Stream s = File.Create(path))
            {
                try
                {
                    FormProps props = new FormProps();
                    props.x = f.Location.X;
                    props.y = f.Location.Y;
                    xs.Serialize(s, props);
                }
                catch
                {
                }
            }
        }
        public static void Deserialize(Form f, string path)
        {
            XmlSerializer xs = new XmlSerializer(typeof(FormProps));
            if (File.Exists(path))
            {
                using (Stream s = File.OpenRead(path))
                {
                    try
                    {
                        FormProps props = (FormProps)xs.Deserialize(s);
                        f.Location = new Point(props.x, props.y);
                    }
                    catch
                    {
                    }
                }
            }
        }
        public class FormProps
        {
            public int x;
            public int y;
        }
    }
}

No comments:

Post a Comment