65.9K
CodeProject is changing. Read more.
Home

Simple class to save your Form's Size To Registry

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (3 votes)

Apr 22, 2011

CPOL
viewsIcon

11338

Simple class to save your Form's Size To Registry

using System;
using System.Windows.Forms;
using Microsoft.Win32;

namespace Chico.Registry
{
    public class SizeRegistry
    {
        private RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default);
        private RegistryKey mKey;
        public SizeRegistry(string subkey)
        {
            mKey = key.CreateSubKey(subkey, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryOptions.Volatile);
            mKey.OpenSubKey(subkey);
            key.Close(); key.Dispose();
        }
        public void GetSize(out int width, out int height)
        {            
            width = (int)mKey.GetValue("FormWidth",320);
            height = (int)mKey.GetValue("FormHeight", 240);           
        }
        public void SetSize(int FormWidth, int FormHeight)
        {           
            mKey.SetValue("FormWidth", FormWidth, RegistryValueKind.DWord);
            mKey.SetValue("FormHeight", FormHeight, RegistryValueKind.DWord);            
        }
        public void Close()
        {
            mKey.Close();           
            mKey.Dispose();            
        }
    }
}
Here is an example of using this class:
using System;
using System.Drawing;
using System.Windows.Forms;
using Chico.Registry;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
       SizeRegistry key = new SizeRegistry(Application.ProductName);
        int width, height;
        public Form1()
        {
            InitializeComponent();
            key.GetSize(out width, out height);
            this.Size = new Size(width, height);            
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            key.SetSize(this.Width, this.Height);
            key.Close();
        }                               
    }
}
Simple class to save your Form's Size To Registry - CodeProject