The registry is a huge database that holds all
necessary the information that the operating system needs to function and
communicate with anything that resides in the computer. It is organized as a
tree view and functions like Windows Explorer. Although it is highly used
by applications installed in the computer, you can use it to store
information related to your application and retrieve that information when
necessary.
Most of the information in the registration is
organized like a dictionary, as a combination of keys and values. In this
exercise, we will create an application with a form that the user can move
while using the application. When the user closes the application, we will
save the location of the form in the registry. The next time the user
opens the application, we will retrieve the previous location and apply it
to the form.
|
Practical Learning: Creating the Application |
|
- Start Microsoft Visual Studio .NET or Visual C# and create a Windows Application named Remember1
- Right-click the body of the form and click View Code
- In the top section of the file, under the other using
lines, type
using Microsoft.Win32;
- Return to the form and click its body
- In the Properties window, click Events and double-click Closing
- Implement the Closing event as follows:
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// When the user closes the application,
// Examine the HKEY_CURRENT_USER key in the registry
// If there is no key named RememberLoc, create it
RegistryKey regKey = Registry.CurrentUser.CreateSubKey("RememberLoc");
// In the RememberLocation key, create a sub-key named Left and
// store the Left position of the form in it
regKey.SetValue("Left", this.Left);
// Create a sub-key named Top and
// store the Top position of the form in it
regKey.SetValue("Top", this.Top);
// Close the registry object
regKey.Close();
}
|
- Execute the application
- Move the form and close it
- Return to the form and double-click its body
- Implement the Load event as follows:
private void Form1_Load(object sender, System.EventArgs e)
{
// Find out if a key named RememberLoc exists in HKEY_CURRENT_USER
// If it exists, open it
RegistryKey regKey = Registry.CurrentUser.CreateSubKey("RememberLoc");
// Retrieve the values of its Left and its Top keys
string L = regKey.GetValue("Left").ToString();
string T = regKey.GetValue("Top").ToString();
// Set the location of the form based on the values
// retrieved from the registry
this.Left = int.Parse(L);
this.Top = int.Parse(T);
// Release the resources that the registry variable was using
regKey.Close();
}
|
- Execute the application again and notice that it remembers where the form
was positioned the last time the application was closed
- Open the registry and examine the HKEY_CURRENT_USER node. Notice that it
has a new node named RememberMe
- Close the registry
|
|