Click here to Skip to main content
15,891,607 members
Articles / Desktop Programming / Windows Forms

Visual Application Launcher

Rate me:
Please Sign up or sign in to vote.
4.91/5 (37 votes)
23 Jan 2012CPOL23 min read 107.6K   3.7K   116  
A WinForms UI using WCF services, Entity Framework, repository data access, repository caching, Unit of Work, Dependency Injection, and every other buzz work you can think of!
namespace VAL.Controls
{
    using System;
    using System.Windows.Forms;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    using System.IO;
    using System.Drawing;
    using System.Security;

    public class PersistWindowState
    {
        private Form parent;

        /// <summary>
        /// Do not use. This is for serializing only.
        /// </summary>
        public PersistWindowState()
        {
        }

        public PersistWindowState(Form form)
        {
            parent = form;

            // subscribe to parent form's events
            parent.Closing += new System.ComponentModel.CancelEventHandler(OnClosing);
            parent.Resize += new System.EventHandler(OnResize);
            parent.Move += new System.EventHandler(OnMove);
            parent.Load += new System.EventHandler(OnLoad);

            // get initial width and height in case form is never resized
            this.Width = parent.Width;
            this.Height = parent.Height;
        }

        /// <summary>
        /// Read only. The Top value of the <see cref="Parent"/> form
        /// </summary>
        public int Top { get; set; }

        /// <summary>
        /// Read only. The Left value of the <see cref="Parent"/> form
        /// </summary> 
        public int Left { get; set; }

        /// <summary>
        /// Read only. The Width value of the <see cref="Parent"/> form
        /// </summary>
        public int Width { get; set; }

        /// <summary>
        /// Read only. The Height value of the <see cref="Parent"/> form
        /// </summary>
        public int Height { get; set; }

        /// <summary>
        /// Read only. The windowstate value of the <see cref="Parent"/> form
        /// </summary>
        public int WindowState { get; set; }

        private void OnResize(object sender, System.EventArgs e)
        {
            // save width and height
            if (parent.WindowState == FormWindowState.Normal)
            {
                this.Width = parent.Width;
                this.Height = parent.Height;
            }
        }

        private void OnMove(object sender, System.EventArgs e)
        {
            // save position
            if (parent.WindowState == FormWindowState.Normal)
            {
                this.Left = parent.Left;
                this.Top = parent.Top;
            }

            // save state
            WindowState = (int)parent.WindowState;
        }

        private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Save();
        }

        private void OnLoad(object sender, System.EventArgs e)
        {
            Load();
        }

        #region Serialization


        /// <summary>
        ///   Loads a the <b>UserOptions</b> file into a new instance.
        /// </summary>
        /// <returns>
        ///   A <see cref="UserOptions"/>.
        /// </returns>
        private void Load()
        {
            if (!File.Exists(StateFilePath)) return;

            XmlSerializer serializer = new XmlSerializer(this.GetType());

            try
            {
                using (FileStream stream = new FileStream(StateFilePath, FileMode.Open))
                {
                    XmlReader reader = new XmlTextReader(stream);
                    PersistWindowState pws = (PersistWindowState)serializer.Deserialize(reader);
                    parent.Location = new Point(pws.Left, pws.Top);
                    parent.Size = new Size(pws.Width, pws.Height);
                    parent.WindowState = (FormWindowState)pws.WindowState;
                }
            }
            catch
            {
                // Definitely just swallow this. I don't want the form not to display
                // for whatever reason,  better it just loses it's last persisted location
                // and recreates
            }

        }

        /// <summary>
        ///   Saves the <see cref="UserOptions"/>
        /// </summary>
        /// <remarks>
        ///   A <see cref="SecurityException"/> is quietly ignored.
        /// </remarks>
        private void Save()
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(this.GetType());
                using (StreamWriter writer = new StreamWriter(StateFilePath))
                {
                    serializer.Serialize(writer, this);
                }
            }
            catch
            {
                // Do nothing, not the end of the world
            }
        }

        /// <summary>
        ///   Gets the fully qualified name of the ".state.xml" file.
        /// </summary>
        /// <remarks>
        ///   If a path does not exist, one is created in the following format:
        ///   <para>
        ///   <see cref="Environment.SpecialFolder">ApplicationData</see>\
        ///    <see cref="Application.CompanyName"/>\ 
        ///    <see cref="Application.ProductName"/>\ 
        ///    <i>appname</i>.options.xml
        ///   </para>
        ///   <para>
        ///    A typical <b>StateFilePath</b>, is 
        ///    "C:\Documents and Settings\<i>username</i>\Application Data\<i>company</i>\<i>product</i>\<i>appname</i>.exe.options.xml".
        ///    </para>
        /// </remarks>
        private string StateFilePath
        {
            get
            {
                // Build the directory.
                StringBuilder path = new StringBuilder();
                path.Append(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
                path.Append(Path.DirectorySeparatorChar);
                path.Append(Application.ProductName);

                string dir = path.ToString();
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);


                // Add the file name.
                path.Append(Path.DirectorySeparatorChar);
                path.Append(parent.Name + @".state.xml");

                return path.ToString();
            }
        }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions