Visual Basic 6 function "RegisterGetKey"

Go back

Below you'll find the source for the Visual Basic 6 function RegisterGetKey.

Attribute VB_Name = "modRegisterGetKey"
' This function is downloaded from:
' http://www.stefanthoolen.nl/archive/vb6-functions/
' 
' You may freely distribute this file but please leave all comments, including this one, in it.
' 
' @Author Stefan Thoolen <mail@stefanthoolen.nl>

Option Explicit

Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal HKEY As Long) As Long

Private Declare Function RegQueryValueExA Lib "advapi32.dll" (ByVal HKEY As Long, ByVal lpValueName As String, ByVal lpReserved As Long, lpType As Long, lpData As Any, lpcbData As Long) As Long

Private Declare Function RegOpenKeyA Lib "advapi32.dll" (ByVal HKEY As Long, ByVal lpSubKey As String, phkResult As Long) As Long

Private Const REG_EXPAND_SZ = 2

Private Const REG_SZ = 1

Public Enum HKEY
    HKEY_CLASSES_ROOT = &H80000000
    HKEY_CURRENT_USER = &H80000001
    HKEY_LOCAL_MACHINE = &H80000002
    HKEY_USERS = &H80000003
    HKEY_CURRENT_CONFIG = &H80000005
End Enum

''
' Gets a registry key
' @param    HKEY    root        The registry root
' @param    String  path        The path to the key we want to read
' @param    String  keyname     The key we want to read
' @return   String              The value of the key
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function RegisterGetKey(ByVal root As HKEY, ByVal path As String, ByVal keyname As String) As String
    Dim result As Long, handle As Long
    Dim retval As String, retlen As Long, rettype As Long
    Dim zeropos As Integer
    
    result = RegOpenKeyA(HKEY_LOCAL_MACHINE, path, handle)
    result = RegQueryValueExA(handle, keyname, 0&, rettype, ByVal 0&, retlen)
    If result = 0 Then ' Success
        If rettype = REG_SZ Or rettype = REG_EXPAND_SZ Then
            retval = String(retlen, " ")
            result = RegQueryValueExA(handle, keyname, 0&, 0&, ByVal retval, retlen)
            zeropos = InStr(retval, Chr(0))
            If zeropos > 0 Then retval = Left(retval, zeropos - 1)
            RegisterGetKey = retval
        End If
    End If
    result = RegCloseKey(handle)
End Function