Accessing the Registry with VB6 and VB.NET

Storing and retrieving information from the Windows Registry will play a major part in any programmer's life. You can store small bits of information, such as recently used files, form sizes and location, and user preferences—to name just a few—in the Windows Registry. My aim with this article is to explain the major differences between the way Visual Basic 6 and Visual Basic .NET utilise the Windows Registry.

Visual Basic 6 and the Windows Registry

Visual Basic 6 comes with four procedures for accessing the Windows Registry:

SaveSetting

The SaveSetting statement is used to store a value in the Registry.

Syntax

SaveSetting VBKeyName, Section, Key, Setting
Term Meaning
SaveSetting Statement name
VBKeyName String value representing the name of the key within the VB/VBA area of the Registry
Section String value representing the section or subkey for the specific application's setting
Key String value that represents the name of a specific entry within the section
Setting String value that you want to store to a given key

Example

'Store Left Value
SaveSetting App.Title, "Form Location", "Left", "250"
'Store Top Value
SaveSetting App.Title, "Form Location", "Top", "300"

GetSetting

You use the GetSetting() function to retrieve a value from a particular section in the Visual Basic key of the Windows Registry.

Syntax

Term Meaning
StringVariable String value returned by the GetSetting() function
GetSetting The name of the function
VBKeyName String value representing the name of the key within the VB/VBA area of the Registry
Section String value representing the section or subkey for the specific applications setting
Key String value that represents the name of a specific entry within the section
Default Optional argument. A String value that represents the value to return if GetSetting() fails or encounters an error. If the function is successful, it returns the string found at the key setting; if it is unsuccessful, it returns the string value assigned to the Default argument

Example

'Variable to hold value returned from the Registry
Dim strTop As String
'Variable to hold value returned from Registry
Dim strLeft As String
'Read Top value stored
strTop = GetSetting(App.Title, "Form Location", "Top")
'Read Left value stored
strLeft = GetSetting(App.Title, "Form Location", "Left")

GetAllSettings

You use GetAllSettings() to retrieve an array from the Registry that contains all the key settings along with their respective values of a particular section in the Registry.

Syntax

VariantVariable = GetAllSettings(VBKeyName, Section)
Term Meaning
VariantVariable An array of values returned by the function, of type Variant
GetAllSettings Function name
VBKeyName String value representing the name of the key within the VB/VBA area of the Registry
Section String value that represents the name of a specific entry within the section

Example

Dim arrAllSettings As Variant    'Variable to store 2 dimensional
                                 'array of values read from the
                                 'Registry

'Retrieve Registry values stored under Form Location
arrAllSettings = GetAllSettings(App.Title, "Form Location")


'Display the first key and first value under Form Location (Left)
txtGetAllSettings.Text = arrAllSettings(0, 0) & " = " & _
   arrAllSettings(0, 1) & vbCrLf
'Display the second key and second value under Form Location (Top)
txtGetAllSettings.Text = txtGetAllSettings.Text & _
   arrAllSettings(1, 0) _
   & " = " & arrAllSettings(1, 1)

DeleteSetting

If you want to delete an entire section from a key, you use the DeleteSetting statement.

Syntax

DeleteSetting VBKeyName, Section [, Key]
Term Meaning
DeleteSetting Statement name
VBKeyName String value representing the name of the key within the VB/VBA area of the Registry
Section String Value representing the section to delete
Key String Value representing a specific subkey to delete. If you do not supply this optional paramater, all the subkeys of the section will be deleted

Example

DeleteSetting App.Title, "Form Location" 'Delete Form Location

These internal Registry functions have one major drawback. Visual Basic can retrieve and store data only to a specific key in the Registry, namely:

MyComputer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings

This process is, unfortunately, automatic to Visual Basic 6; Visual Basic 6 cannot write to or read from any other keys in the Windows Registry without the aid of the Windows API, functions such as:

Sample Application

The first sample application (RegistryVB6) accompanying this article shows in detail how the intrinsic Visual Basic 6 Registry functions are used to store and retrieve values in the Registry. The sample application also shows in detail how to use the necessary API functions to store values in the Registry and read from the Registry.

On the next page, I will explain how Visual Basic.NET accesses the Windows Registry.

Accessing the Registry with VB6 and VB.NET

Visual Basic.NET and the Windows Registry

In Visual Basic .NET, the following functions also are used to store and retrieve values from the Registry:

  • SaveSetting
  • GetSetting
  • GetAllSettings
  • DeleteSetting

These keys still utilise the HKEY_CURRENT_USER\Software\VB and VBA Program Settings Registry key to store and retrieve values.

SaveSetting

Example

SaveSetting("Registry Example", "Form Location", "Left", 200)

GetSetting

Example

Dim strLeft As String    'Variable to hold value returned from
                         'Registry
'Read Left value stored
strLeft = GetSetting("Registry Example", "Form Location", "Left")

GetAllSettings

Example

' Object to hold 2-dimensional array returned by GetAllSettings.

Dim arrSettings(,) As String
' Retrieve the settings.

arrSettings = GetAllSettings("Registry Example", "Form Location")
txtGetAllSettings.Text = arrSettings(0, 0) & " = " & _
   arrSettings(0, 1) & vbCrLf         'left
txtGetAllSettings.Text = txtGetAllSettings.Text & _
   arrSettings(1, 0) _
   & " = " & arrSettings(1, 1)        'top

DeleteSetting

Example

DeleteSetting("Registry Example")

As you probably noticed, there virtually is not much difference in the Visual Basic 6 and Visual Basic .NET functions. The only minor difference was with the Multidimensional array declaration; besides that, everything still is the same.

Visual Basic .NET introduces two new intrinsic Registry functions, namely UserAppDataRegistry and CommonAppDataRegistry.SetValue, that also store and retrieve values in the Registry. Take a closer look at these.

CommonAppDataRegistry

The CommonAppDataRegistry property returns the Registry key that is used to store non-user specific and non-roaming data for the machine; the Registry key takes the form:

HKEY_LOCAL_MACHINE\Software\[Control.CompanyName]\
                            [Control.ProductName]\
                            [Control.ProductVersion]

UserAppDataRegistry

The UserAppDataRegistry property returns the Registry key that is used to store roaming data (settings that are specific to a user but machine independent) for each user; the Registry key takes the form:

HKEY_CURRENT_USER\Software\[Control.CompanyName]\
                           [Control.ProductName]\
                           [Control.ProductVersion].

UserAppDataRegistry.SetValue

Example

'Store a Value in HKEY_CURRENT_USER\Software
Application.UserAppDataRegistry.SetValue("Form Display", _
                                         "Test Caption")

UserAppDatRegistry.GetValue

Example

'Variable to store value read from Registry
Dim strFormText As String

'Determine whether or not the Form Display Key actually exists
If Not (Application.UserAppDataRegistry.GetValue("Form Display") _
        Is Nothing) Then
'If the Form Display Key exists

'Store value read in strFormText
strFormText = Application.UserAppDataRegistry.GetValue _
   ("Form Display").ToString()
Me.Text = strFormText    'Assign the value to the Form
Else

'The Form Display Key does not exist

Me.Text = "Key Does Not Exist Yet!"
End If

It is always best to determine whether or not the particular Registry setting is present before referencing it. If you were to omit the simple test, the Application will throw an exception.

Thus far, I have covered the Visual Basic .NET intrinsic Registry functions. Now, you may ask, what if you don't want to store your application settings in either of the above-mentioined Registry keys? The answer to your question is the Win32 Namespace included with the .NET Framework; it includes the Registry and RegistryKey classes.

Registry Class

Term Meaning
ClassesRoot Defines the types of documents and the properties associated with those types
CurrentConfig Contains hardware configuration information that is not user-specific
CurrentUser Contains information about the current user preferences, such as environmental variables
DynData Contains dynamic Registry data, such as that used by Virtual Device Drivers
LocalMachine Contains five subkeys (Hardware, SAM, Security, Software, and System) that hold the configuration data for the local machine
PerformanceData Contains performance information for software components
Users Contains information about the default user preferences

To make use of the Win32 Registry functions, you need to add the following line on top of your Visual Basic.NET module.

Imports Microsoft.Win32

Once that is done, you can use the Win32 Registry functions as follows:

Create a New Registry Key

' Create a new key under HKEY_LOCAL_MACHINE\Software

'true = writeable
Dim Mykey As RegistryKey = _
   Registry.LocalMachine.OpenSubKey("Software", True)
' Add one more sub key 

Dim newkey As RegistryKey = Mykey.CreateSubKey("Registry Example")
' Set value of sub key

newkey.SetValue("Registry Example", "Testing123")

Read from the Registry

'Open the HKEY_LOCAL_MACHINE\Software\Registry Example key

Dim NewKey As RegistryKey = _
   Registry.LocalMachine.OpenSubKey("Software\\Registry Example", _
                                    True)
'Get value stored, and use a Type Conversion function to convert
'the Value from the Registry to a String

Dim GetVal As String = CType(NewKey.GetValue("Registry Example"), _
                             String)
'Display the value on the Titlebar of the Form

Me.Text = GetVal

Delete a Value in a Specific Key

'Open the HKEY_LOCAL_MACHINE\Software\Registry Example key

Dim DelValue As RegistryKey = _
   Registry.LocalMachine.OpenSubKey("Software\\Registry Example", _
                                    True)
'Delete a value in a Key

DelValue.DeleteValue("Registry Example")

Delete a Registry Key

'Open the HKEY_LOCAL_MACHINE\Software\Registry Example key

Dim DelKey As RegistryKey = _
   Registry.LocalMachine.OpenSubKey("Software", True)
'Delete the Registry Example key from HKEY_LOCAL_MACHINE\Software

DelKey.DeleteSubKey("Registry Example")

Sample Application

The second sample application (VBNETRegistry) included with this article demonstrates all the above methods to utilise the Windows Registry productively.

Conclusion

Although the Registry is a big topic to talk about, I hope that this article has been informative about the various options available for utilising the Registry in Visual Basic 6 and Visual Basic .NET productively.



About the Author

Hannes du Preez

Hannes du Preez is a Microsoft MVP for Visual Basic. He is a trainer at a South African-based company. He is the co-founder of hmsmp.co.za, a community for South African developers.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds