Click here to Skip to main content
15,893,266 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Simple class to save your Form's Size To Registry

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
22 Apr 2011CPOL 4K   1  
I just whipped this up EditPlus so there may be some syntax errors.using System;using System.Drawing;using System.Windows.Forms;using Microsoft.Win32; namespace Chico.Registry{ public struct SizeRegistry : IDisposable { private const string kWidthName =...
I just whipped this up EditPlus so there may be some syntax errors.

using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Win32;
 
namespace Chico.Registry
{
    public struct SizeRegistry : IDisposable
    {
	private const string kWidthName = "FormWidth",
			kHeightName = "FormHeight";

        private RegistryKey mKey;

        public SizeRegistry(string subkey)
        {
			using (var key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default))
			{
				mKey = key.CreateSubKey(subkey, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryOptions.Volatile);
				mKey.OpenSubKey(subkey);
			}
        }

		public Size GetSize()
		{
			int w, h;
			w = (int)mKey.GetValue(kWidthName, 320);
			h = (int)mKey.GetValue(kHeightName, 240);

			return new Size(w, h);
		}
		public void SetSize(Size size)
		{
			mKey.SetValue(kWidthName, size.Width, RegistryValueKind.DWord);
			mKey.SetValue(kHeightName, size.Height, RegistryValueKind.DWord); 
		}

        public void Dipose()
        {
            mKey.Close();           
            mKey.Dispose();            
        }

		public static void StreamFormState(Form f, string subkey, bool is_opening)
		{
			using (var sr = new SizeRegistry(subkey))
			{
				if (is_opening)
					f.Size = sr.GetSize();
				else
					sr.SetSize(f.Size);
			}
		}
    };
}

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
		static readonly string kSizeSubkeyName = Application.ProductName;

		public Form1()
        {
            InitializeComponent();
			SizeRegistry.StreamFormState(this, kSizeSubkeyName, true);         
        }
        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
			SizeRegistry.StreamFormState(this, kSizeSubkeyName, false);
        }                               
    };
}

License

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


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

Comments and Discussions

 
-- There are no messages in this forum --