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++ .NET and create a Windows
Forms 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 namespace
lines, type
using namespace 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:
System::Void Form1_Closing(System::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 RememberMe, create it
RegistryKey *regKey = Registry::CurrentUser->CreateSubKey(S"RememberMe");
// In the RememberLocation key, create a sub-key named Left and
// store the Left position of the form in it
regKey->SetValue(S"Left", __box(this->Left));
// Create a sub-key named Top and
// store the Top position of the form in it
regKey->SetValue(S"Top", __box(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:
System::Void Form1_Load(System::Object * sender, System::EventArgs * e)
{
// Find out if a key named RememberMe exists in HKEY_CURRENT_USER
// If it exists, open it
RegistryKey *regKey = Registry::CurrentUser->CreateSubKey(S"RememberMe");
// Retrieve the values of its Left and its Top keys
String* L = regKey->GetValue(S"Left")->ToString();
String* T = regKey->GetValue(S"Top")->ToString();
// Set the location of the form based on the values
// retrieved from the registry
this->Left = L->ToInt32(0);
this->Top = T->ToInt32(0);
// 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
|
|