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
{
public class SizeRegistry : IDisposable
{
private RegistryKey mKey;
public SizeRegistry(string subkey)
{
try
{
using (RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default))
{
mKey = key.CreateSubKey(subkey, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryOptions.Volatile);
mKey.OpenSubKey(subkey);
}
}
catch (Exception ex) { throw ex; }
}
~SizeRegistry()
{
this.Dispose();
}
public Size GetSize()
{
Size storedSize = new Size();
try
{
if (mKey != null)
{
storedSize.Height = (int)mKey.GetValue("FormWidth");
storedSize.Width = (int)mKey.GetValue("FormHeight");
}
}
catch (Exception ex) { throw ex; }
return storedSize;
}
public void SetSize(Size formSize)
{
try
{
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
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();
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
try
{
using (SizeRegistry key = new SizeRegistry(Application.ProductName))
{
this.Size = key.GetSize();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
using (SizeRegistry key = new SizeRegistry(Application.ProductName))
{
key.SetSize(this.Size);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.