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.
First, let me say that I would not recommend using the registry for this purpose. The registry is fraught with pitfalls to accommodate some really complex scenarios that you probably don’t want to mess with just so you can persist your form size. I would think that a user scoped configuration...
First, let me say that I would not recommend using the registry for this purpose. The registry is fraught with pitfalls to accommodate some really complex scenarios that you probably don’t want to mess with just so you can persist your form size. I would think that a user scoped configuration setting may be a more appropriate way to go: Read here for more - http://msdn.microsoft.com/en-us/library/k4s6c3a0.aspx[^] .
 
However, if you absolutely HAVE to use this method, I would recommend implementing IDisposable and a finalizer method to the class you have created. This is due to the fact that the class is centered on the RegistryKey object which is a disposable object, and we want to follow the right pattern. Also, you will want to implement at least SOME exception handling. Since you are working with the registry, a highly secured place, you have a very high chance of exceptions occurring.
 
Here is an example:
using System;
using Microsoft.Win32;
using System.Drawing;
 
namespace Chico.Registry 
{ 
// Implement IDisposable
public class SizeRegistry : IDisposable
    {
        private RegistryKey mKey;
 
        public SizeRegistry(string subkey)
        {
            try
            {
                // Move the 'OpenBaseKey' operation to the constructor and wrap it in a using statement.  It is a disposable object and only used once.
                using (RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default))
                {
                    mKey = key.CreateSubKey(subkey, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryOptions.Volatile);
                    mKey.OpenSubKey(subkey);
                }
            }
            // You can implement some more handling, for now, we will just throw our exceptions
            catch (Exception ex) { throw ex; }
 
        }
        // create a finalizer method that gets called if you forget to manually dispose of the object yourself
        ~SizeRegistry()
        {
            // This will just call its own dispose method
            this.Dispose();
        }
 
        // Since this class is meant for a very narrow purpose (sizes) just use the System.Drawing.Size class to pass back a complex type rather than using the out directive on your parameters.
        public Size GetSize()
        {
            Size storedSize = new Size();
            try
            {
                // Make sure you actually have a usable RegistryKey object!
                if (mKey != null)
                {
                    storedSize.Height = (int)mKey.GetValue("FormWidth");
                    storedSize.Width = (int)mKey.GetValue("FormHeight");
                }
            }
            catch (Exception ex) { throw ex; }
 
            return storedSize;
        }
 
        // Again, we know that we are dealing with sizes, just use the Size type.
        public void SetSize(Size formSize)
        {
            try
            {
                // Make sure you actually have a usable RegistryKey object, and a real Size!
                if (mKey != null && !formSize.IsEmpty)
                {
                    mKey.SetValue("FormWidth", formSize.Width, RegistryValueKind.DWord);
                    mKey.SetValue("FormHeight", formSize.Height, RegistryValueKind.DWord);
                }
            }
            catch (Exception ex) { throw ex; }
        }
 
        #region IDisposable Members
 
        // Your dispose method that will clean things up when youre done with it
        public void Dispose()
        {
            if (mKey != null)
            {
                mKey.Close();
                mKey.Dispose();
            }
        }
 
        #endregion
    }
}
 
Now, lets see how we would use this class in our form:
 
using System; 
using System.Drawing; 
using System.Windows.Forms; 
using Chico.Registry; 
 
namespace WindowsFormsApplication1 
{ 
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            // Add our event handler for the form closing
            this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
 
            // Since your new class is only going to ever be used twice in your application (start and stop), it doesn't make much sense to hold it open the entire life of the application.  Wrap it in a using block, this will take advantage of the IDisposable method we implemented.  Also, don't forget your exception handling!
            try
            {
            using (SizeRegistry key = new SizeRegistry(Application.ProductName))
            {
                this.Size = key.GetSize();
            }
            }
            catch (Exception ex)
            {
                // We will just display the exception to the user and continue.
                MessageBox.Show(ex.Message);
            }
        }
 
        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
 
            // Implement the same using pattern as in the constructor to save the size
            try
            {
            using (SizeRegistry key = new SizeRegistry(Application.ProductName))
            {
                key.SetSize(this.Size);
            }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
 
        }
    }
}

License

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

Share

About the Author

Karl Sanford
Software Developer Open Systems Technologies
United States United States
First learned to program in 1997 on my TI-83 and have been doing it ever since, with a foray into networking and infrastructure.
 
Mostly a C# junky (Win\Web Forms, WP7.5/8, WPF and MVC), though I have experience with many other technologies and products.
 
I have also been trying to learn and apply more in the area of AI; focusing on computer vision, natural language processing, and classification.
 
In my spare time, I love to tinker with electronics and various useless DIY projects.
 
My brain is a shark... if it stops moving, it will die. I'm always looking to learn more.
Follow on   Twitter   LinkedIn

Comments and Discussions

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