ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Load & Save form configuration

This extension methods allows you to load/save location, size and window state (normal, maximized, minimized) of any form to single XML file at program runtime.

Source

using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace FormExtensions
{
    [Serializable]
    public class FormSettings
    {
        public FormWindowState WindowState { get; set; }
        public Size Size { get; set; }
        public Point Location { get; set; }
    }

    public static class FormExtensions
    {
        public static void LoadSettings(this Form form, string path)
        {
            if (File.Exists(path))
            {
                using (var sr = new StreamReader(path))
                {
                    XmlSerializer xmlser = new XmlSerializer(typeof(FormSettings));
                    var formSettings = (FormSettings)xmlser.Deserialize(sr);
                    if (formSettings != null)
                    {
                        form.Size = formSettings.Size;
                        form.Location = formSettings.Location;
                        form.WindowState = formSettings.WindowState;
                    }
                }
            }
        }

        public static void SaveSettings(this Form form, string path)
        {
            FormSettings formSettings = new FormSettings();
            formSettings.WindowState = form.WindowState;
            if (form.WindowState == FormWindowState.Normal)
            {
                formSettings.Size = form.Size;
                formSettings.Location = form.Location;
            }
            else
            {
                formSettings.Size = form.RestoreBounds.Size;
                formSettings.Location = form.RestoreBounds.Location;
            }
            using (var sw = new StreamWriter(path))
            {
                XmlSerializer xmlSer = new XmlSerializer(typeof(FormSettings));
                xmlSer.Serialize(sw, formSettings);
            }
        }
    }
}

Example

You can load and save form settings by calling methods directly from any place of code:
frmInstance.LoadSettings(@"D:\form.xml");
frmInstance.SaveSattings(@"D:\form.xml");

...or you can override OnLoad & OnClosed methods of any form to load/save settings automatically:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    //...
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        this.LoadSettings(@"D:\form.xml");
    }

    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        this.SaveSettings(@"D:\form.xml");
    }
    //...
}

Author: Marcin Kozub

Submitted on: 26 jul. 2013

Language: C#

Type: System.Windows.Forms.Form

Views: 5181