Save and Restore Form Position and Size

前端 未结 8 2183
说谎
说谎 2020-12-14 04:36

In a WinForms 2.0 C# application, what is the typical method used for saving and restoring form position and size in an application?

Related, is it possible to add n

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 05:30

    I got this code from somewhere, but unfortunately at the time (long ago) didn't make a comment about where I got it from.

    This saves the form info to the user's HKCU registry:

    using System;
    using System.Windows.Forms;
    using Microsoft.Win32;
    
    /// Summary description for FormPlacement.
    public class PersistentForm : System.Windows.Forms.Form
    {
        private const string DIALOGKEY = "Dialogs";
    
        /// 
        protected override void OnCreateControl()
        {
            LoadSettings();
            base.OnCreateControl ();
        }
    
        /// 
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            SaveSettings();
            base.OnClosing(e);
        }
    
        /// Saves the form's settings.
        public void SaveSettings()
        {
            RegistryKey dialogKey = Application.UserAppDataRegistry.CreateSubKey(DIALOGKEY);
            if (dialogKey != null)
            {
                RegistryKey formKey = dialogKey.CreateSubKey(this.GetType().ToString());
                if (formKey != null)
                {
                    formKey.SetValue("Left", this.Left);
                    formKey.SetValue("Top", this.Top);
                    formKey.Close();
                }
                dialogKey.Close();
            }
        }
    
        /// 
        public void LoadSettings()
        {
            RegistryKey dialogKey = Application.UserAppDataRegistry.OpenSubKey(DIALOGKEY);
            if (dialogKey != null)
            {
                RegistryKey formKey = dialogKey.OpenSubKey(this.GetType().ToString());
                if (formKey != null)
                {
                    this.Left = (int)formKey.GetValue("Left");
                    this.Top = (int)formKey.GetValue("Top");
                    formKey.Close();
                }
                dialogKey.Close();
            }
        }
    }
    

提交回复
热议问题