Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

Simple class to save your Form's Size To Registry

, 22 Apr 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

kornman00

United States United States
No Biography provided
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411022.1 | Last Updated 22 Apr 2011
Article Copyright 2011 by kornman00
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid