Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Visual Basic
Expertise: Beginner
Jul 24, 1997

Searching the Registry

Question:
Using VB 5.0, how can I detect the default browser and launch it to go to user selected site?

Answer:
This information is located in the Registry under this key: HKEY_CLASSES_ROOT\HTMLFile\Shell\Open\Command To read it, you need to use the Registry API. The following is a section from my new book discussing the Registry API and how to use it. Sorry for the bad formatting, but I had to copy it from Microsoft Word. You should be able to find your way through it.

The first function we need is one to retrieve information. There are actually several different API calls involved to do this, so we're going to encapsulate them all in a simple function that you can use in any application you have.

To get started, do the following:

  1. Open up your Bookmark Viewer program and create a new code module. Since you'll probably want to use this code in another application, we don't want to clutter the Bookmark Viewer variables file with this code.
  2. The GetRegistryKey function code is listed below:
    Public Function GetRegistryKey(sKeyName As String, _
       sValue As String, _
       Optional bClasses_Root As Boolean = False, _
       Optional bCurrent_User As Boolean = False, _
       Optional bLocal_Machine As Boolean = False, _
       Optional bUsers As Boolean = False, _
       Optional bCurrent_Config As Boolean = False, _
       Optional bDyn_Data As Boolean = False) As String
       
       Dim sReturnBuffer As String
       Dim iBufLen As Long
       Dim iReturn As Long
       Dim iTree As Long
       Dim hKeyHandle As Long
       
       If bClasses_Root Then
          iTree = HKEY_CLASSES_ROOT
       ElseIf bCurrent_User Then
          iTree = HKEY_CURRENT_USER
       ElseIf bLocal_Machine Then
          iTree = HKEY_LOCAL_MACHINE
       ElseIf bUsers Then
          iTree = HKEY_USERS
       ElseIf bCurrent_Config Then
          iTree = HKEY_CURRENT_CONFIG
       ElseIf bDyn_Data Then
          iTree = HKEY_DYN_DATA
       Else
          GetRegistryKey = ""
          Exit Function
       End If
       '
       ' Set up return buffer
       '
       sReturnBuffer = Space(BUFFER_LENGTH)
       iBufLen = BUFFER_LENGTH
       
       iReturn = RegOpenKeyEx(iTree, sKeyName, _
          0, KEY_ALL_ACCESS, hKeyHandle)
       
       If iReturn = ERROR_SUCCESS Then
          iReturn = RegQueryValueExString(hKeyHandle, _
             sValue, 0, 0, sReturnBuffer, iBufLen)
          If iReturn = ERROR_SUCCESS Then
             GetRegistryKey = Left$(sReturnBuffer, _
                iBufLen - 1)
          Else
             GetRegistryKey = ""
          End If
       Else
          GetRegistryKey = ""
       End If
       RegCloseKey hKeyHandle
       
    End Function
    
    Before we jump into this function, let's take a quick look at a real registry key and settings. Start the Registry Editor and find your way down to this key:
    HKEY_CURRENT_USER\Software\Microsoft\MS Setup (ACME)\User Info
    
    Once you click on that key, values will be displayed in the right hand side of the window. The GetRegistryKey function mimics what you just did:
    • You found the key in the registry.
    • You looked at the values in that key.
    • You closed the Registry (and the key)
    If you understand that process, the code is going to be a breeze. The first long If/Then block determines which section of the registry the key is in. The six optional parameters correspond to the six sections of the Windows 95 registry. Windows NT has additional sections, but we won't be covering those here.

    Based on which section the user specified, a constant value is stored in the iTree variable for later use. Next, we create a return buffer for the API call to put its data into. For any API call that returns data you must create a buffer in exactly this way or you run the risk of crashing your program.

    The next statement actually calls the API function to open the key. If we were trying to get to the key we just looked at, we could send in either of these two strings:

    \Software\Microsoft\MS Setup (ACME)\User Info
    Software\Microsoft\MS Setup (ACME)\User Info
    
    
    The Registry functions are case insensitive and do not care if you have a backslash at the beginning or end of the key value.

    If that call was successful, two things have happened:

    • A successful return code was put in the iReturn variable.
    • A handle, or reference, to the key was stored in the hKeyHandle variable.
    We can now retrieve particular values from that key using the RegQueryValueExString API call. That API call uses the handle from the previous call and returns the values in the buffer we created earlier.

    If that call was also successful, we need to trim off the null terminator at the end of the buffer. In case you're not a C/C++ programmer, a null terminator is how C programmers mark the end of a string. Unfortunately, that character makes it back to VB-land so we have to trim it off. Luckily the RegQueryValueExString API call sets the iBufLen variable to the length of the string it returned, which includes the null character. A quick call to the Left$ function trims the string right up. Finally a call to RegCloseKey cleans up the reference to the Registry and we're all done!

  3. Before you can use this code, you have to add quite a few constants and API declarations at the beginning of your code module. These are listed here for your convenience:
    Private Declare Function RegCloseKey Lib "advapi32.dll" _
       (ByVal hKey As Long) As Long
    
    Private Declare Function RegCreateKeyEx Lib _
       "advapi32.dll" _
       Alias "RegCreateKeyExA" _
       (ByVal hKey As Long, ByVal lpSubKey As String, _
       ByVal Reserved As Long, ByVal lpClass As String, _
       ByVal dwOptions As Long, ByVal samDesired As Long, _
       lpSecurityAttributes As Any, _
       hKeyHandle As Long, lpdwDisposition As Long) As Long
    
    Private Declare Function RegQueryValueExString Lib _    
       "advapi32.dll" _
       Alias "RegQueryValueExA" _
       (ByVal hKey As Long, ByVal lpValueName As String, _
       ByVal lpReserved As Long, lpType As Long, _
       ByVal lpData As String, lpcbData As Long) As Long
       
    Private Declare Function RegOpenKeyEx Lib _
       "advapi32.dll"_
       Alias "RegOpenKeyExA" _
       (ByVal hKey As Long, ByVal lpSubKey As String, _
       ByVal ulOptions As Long, ByVal samDesired As Long, _
       hKeyHandle As Long) As Long
       
    Private Declare Function RegSetValueEx Lib "advapi32.dll" _
       Alias "RegSetValueExA" _
       (ByVal hKey As Long, ByVal lpValueName As String, _
       ByVal Reserved As Long, ByVal dwType As Long, _
       lpData As Any, ByVal cbData As Long) As Long
    
    Public Const ERROR_SUCCESS = 0&
    
    Public Const HKEY_CLASSES_ROOT = &H80000000
    Public Const HKEY_CURRENT_CONFIG = &H80000005
    Public Const HKEY_CURRENT_USER = &H80000001
    Public Const HKEY_DYN_DATA = &H80000006
    Public Const HKEY_LOCAL_MACHINE = &H80000002
    Public Const HKEY_USERS = &H80000003
    
    Public Const KEY_CREATE_SUB_KEY = &H4
    Public Const KEY_ENUMERATE_SUB_KEYS = &H8
    Public Const KEY_QUERY_VALUE = &H1
    Public Const KEY_SET_VALUE = &H2
    Public Const KEY_NOTIFY = &H10
    Public Const KEY_CREATE_LINK = &H20
    Public Const REG_OPTION_NON_VOLATILE = 0
    Public Const REG_SZ = 1
    Public Const STANDARD_RIGHTS_ALL = &H1F0000
    Public Const SYNCHRONIZE = &H100000
    
    Private Const BUFFER_LENGTH = 255
    
    
    Public Const KEY_ALL_ACCESS = ((STANDARD_RIGHTS_ALL Or _
       KEY_QUERY_VALUE Or _
       KEY_SET_VALUE Or _
       KEY_CREATE_SUB_KEY Or _
       KEY_ENUMERATE_SUB_KEYS Or _
       KEY_NOTIFY Or _
       KEY_CREATE_LINK) And (Not SYNCHRONIZE))
    
    
    Note that some of these API calls have not yet been used. They will be used in the SaveRegistryKey function we'll build next. To test out your function, you can add the following statement somewhere in your code. This will retrieve the default web browser. You can use this in a Shell statement to start a browser for a web site, if need be.
    Debug.Print GetRegistryKey("htmlfile\shell\open\command", "", _
          bClasses_Root:=True)
    
    This will print a result similar to this on your debug window.
    "F:\COMMUN~1\INTERN~1\iexplore.exe" -nohome
    
    Regardless of what it prints, it will match exactly with the key value at HKEY_CLASSES_ROOT\htmlfile\shell\open\command. In this case, we used a blank value name since we were looking for the default value of the key.
  4. With the GetRegistryKey function out of the way, let's look at the SaveRegistryKey function listed here:
    Public Sub SaveRegistryKey(sKey As String, _
       sValueName As String, sNewValue As String, _
       Optional bClasses_Root As Boolean = False, _
       Optional bCurrent_User As Boolean = False, _
       Optional bLocal_Machine As Boolean = False, _
       Optional bUsers As Boolean = False, _
       Optional bCurrent_Config As Boolean = False, _
       Optional bDyn_Data As Boolean = False)
    
       Dim sKeyName As String
       Dim iReturn As Long
       Dim iTree As Long
       Dim hKeyHandle As Long
       
       If bClasses_Root Then
          iTree = HKEY_CLASSES_ROOT
       ElseIf bCurrent_User Then
          iTree = HKEY_CURRENT_USER
       ElseIf bLocal_Machine Then
          iTree = HKEY_LOCAL_MACHINE
       ElseIf bUsers Then
          iTree = HKEY_USERS
       ElseIf bCurrent_Config Then
          iTree = HKEY_CURRENT_CONFIG
       ElseIf bDyn_Data Then
          iTree = HKEY_DYN_DATA
       Else
          Exit Sub
       End If
       
       '
       ' RegCreateKeyEx will open the named key if it exists, 
       ' and create a new one if it doesn't.
       '
       iReturn = RegCreateKeyEx(iTree, sKey, 0&, _
          vbNullString, REG_OPTION_NON_VOLATILE, _
          KEY_ALL_ACCESS, 0&, hKeyHandle, iReturn)
       
       '
       ' RegSetValueEx saves the value to the string within 
       ' the key that was just opened.
       '
       iReturn = RegSetValueEx(hKeyHandle, sValueName, 0&, _
          REG_SZ, ByVal sNewValue, Len(sNewValue))
       
       '
       ' Close the key
       '
       RegCloseKey hKeyHandle
       
    End Sub
    
    As you might have guessed, this function is nearly the reverse of the GetRegistryKey function. If the key doesn't already exist, we have to create it. If it is there, we need to open it. Luckily, the RegCreateKeyEx API call will do the right thing as needed; that is, it will build a new key if necessary or open an existing one. We then set the value and close the key. Somewhere in your code, let's change your default username with the following call:
    SaveRegistryKey _
       "\Software\Microsoft\MS Setup (ACME)\User Info", 
       "DefName", _
       "Bill Gates"
    
    You can now go out to the registry and see that change in that key.

    Now that you have the power to read and edit the registry from code, one word of caution: the Registry is EXTREMELY fragile. One modified key in the wrong place and you will be stuck reinstalling Windows from scratch. If you don't know what a key does or it doesn't make sense why it is in your Registry, leave it alone. What you don't know can kill your system.

    With that caveat out of the way, here are some interesting keys to use for various system functions.

    • \Software\Microsoft\MS Setup (ACME)\User Info - These values store the default Windows user and company names which are commonly used by setup programs. Located under the HKEY_CURRENT_USER tree.
    • \HTMLFile\Shell\Open\Command - Retrieves the default web browser, just like if you had double-clicked an HTML file in Windows Explorer. Located under the HKEY_CLASSES_ROOT tree.
    • \Software\VB and VBA Program Settings - This is the area where all GetSetting and SaveSetting function calls read and write from. This is located under the HKEY_CURRENT_USER tree.
    • \Word.Document.8\Shell\Open\Command - This is the command line to start Word 97. You can append your own file name to the results of GetRegistryKey. This key is located in the HKEY_CLASSES_ROOT tree.
    • \Software\Microsoft\Windows\CurrentVersion\Uninstall - Ever wonder why programs keep showing up in the Add/Remove Programs dialog under the Control Panel? If you want to permanently remove a program from showing up there, remove its key from here. This key is located in the HKEY_LOCAL_MACHINE tree.

      If you decide to use these functions in your own application, be sure that you follow the standard for locating your keys. The standard is to create a company key under \Software, as in \Software\Microsoft. The next part of the key is the application name. After that, it's up to you. You can have as many levels as necessary. Take a look at \Software\Microsoft\Windows for an example of a huge tree.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date