1. Technology

Programming the Registry using VB 6 and VB.NET

On To Registry Programming ...


Reading and writing data to the registry is possible in both VB 6 and VB.NET using standard Visual Basic functions (That is, not using Windows API calls - see my articles, A Guide to the Win32 API and VB.NET, SetEnvironmentVariable, and the Windows API.) VB 6, however, doesn't really allow you to do much except read and write your own program data using the registry. In other words, VB 6 treats it like a giant "INI" file.

Suppose, for example, that you need to save the current state of the mouse pointer in a VB 6 program. You might want to do this if you're writing a program that allows the user to click anywhere in a form and you want to save all of the information about each click. You can use the VB 6 SaveSetting statement to add this data to the registry and GetSetting to retrieve it again.

The syntax of the SaveSetting function is ...

SaveSetting AppName, Section, Key, Setting

Here's some code that will do the trick:

Dim ClickCounter As Integer
Private Sub Form_Load()
ClickCounter = 0
End Sub
Private Sub Form_MouseDown(button As Integer, _
   shift As Integer, x As Single, y As Single)
   ClickCounter = ClickCounter + 1
   SaveSetting "AboutVBExample", _
         "Location\Click" & ClickCounter, _
         "button", button
   SaveSetting "AboutVBExample", _
         "Location\Click" & ClickCounter, _
         "shift", shift
   SaveSetting "AboutVBExample", _
         "Location\Click" & ClickCounter, _
         "x", x
   SaveSetting "AboutVBExample", _
         "Location\Click" & ClickCounter, _
         "y", y
End Sub

Notice that I create a a sub-section by simply including a backslash in the string passed as the Section parameter and create new entries automatically with a counter. The result in the registry is shown below.

Click Here to display the illustration
Click the Back button on your browser to return

Retrieving the value is just as simple ...

result = GetSetting("AboutVBExample", _
   "Location\Click4", _
   "button", "No Value There!")
Debug.Print result

The last parameter is the default value to be returned if the value can't be retrieved.

GetAllSettings and DeleteSetting complete the set of VB 6 tools.

You might notice that the higher key values shown in the illustration ...

HKEY_CURRENT_USER\Software\VB and VBA Program Settings

... are never specified in the code. The reason is that VB 6 can only read and write this part of the registry. That's why, to VB 6, the registry is sort of a big "INI" file. To do more, we need .NET!

  1. About.com
  2. Technology
  3. Visual Basic
  4. Using VB.NET
  5. Programming the Registry using VB 6 and VB.NET

©2014 About.com. All rights reserved.