Solved

Reading the Registry using VB6

Posted on 2003-11-12
8
3,863 Views
Last Modified: 2012-05-04
Hi,

I need to read from the registry using VB6. I have tried using GetSetting function but that did not help.
For example I need to read the value of the key HKEY_LOCAL_MACHINE\SOFTWARE\XXXSOFT\XYZSOFT_HOME

Any help is welcome

Thanks...
0
Comment
Question by:kaima
8 Comments
 
LVL 53

Accepted Solution

by:
Dhaest earned 20 total points
ID: 9730895
Read a registry key:

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, phkResult As Long) As Long
Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As _
    Long
Private Declare Function RegQueryValueEx Lib "advapi32.dll" Alias _
    "RegQueryValueExA" (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 Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dest As _
    Any, source As Any, ByVal numBytes As Long)

Const KEY_READ = &H20019  ' ((READ_CONTROL Or KEY_QUERY_VALUE Or
                          ' KEY_ENUMERATE_SUB_KEYS Or KEY_NOTIFY) And (Not
                          ' SYNCHRONIZE))

Const REG_SZ = 1
Const REG_EXPAND_SZ = 2
Const REG_BINARY = 3
Const REG_DWORD = 4
Const REG_MULTI_SZ = 7
Const ERROR_MORE_DATA = 234

' Read a Registry value
'
' Use KeyName = "" for the default value
' If the value isn't there, it returns the DefaultValue
' argument, or Empty if the argument has been omitted
'
' Supports DWORD, REG_SZ, REG_EXPAND_SZ, REG_BINARY and REG_MULTI_SZ
' REG_MULTI_SZ values are returned as a null-delimited stream of strings
' (VB6 users can use SPlit to convert to an array of string)

Function GetRegistryValue(ByVal hKey As Long, ByVal KeyName As String, _
    ByVal ValueName As String, Optional DefaultValue As Variant) As Variant
    Dim handle As Long
    Dim resLong As Long
    Dim resString As String
    Dim resBinary() As Byte
    Dim length As Long
    Dim retVal As Long
    Dim valueType As Long
   
    ' Prepare the default result
    GetRegistryValue = IIf(IsMissing(DefaultValue), Empty, DefaultValue)
   
    ' Open the key, exit if not found.
    If RegOpenKeyEx(hKey, KeyName, 0, KEY_READ, handle) Then
        Exit Function
    End If
   
    ' prepare a 1K receiving resBinary
    length = 1024
    ReDim resBinary(0 To length - 1) As Byte
   
    ' read the registry key
    retVal = RegQueryValueEx(handle, ValueName, 0, valueType, resBinary(0), _
        length)
    ' if resBinary was too small, try again
    If retVal = ERROR_MORE_DATA Then
        ' enlarge the resBinary, and read the value again
        ReDim resBinary(0 To length - 1) As Byte
        retVal = RegQueryValueEx(handle, ValueName, 0, valueType, resBinary(0), _
            length)
    End If
   
    ' return a value corresponding to the value type
    Select Case valueType
        Case REG_DWORD
            CopyMemory resLong, resBinary(0), 4
            GetRegistryValue = resLong
        Case REG_SZ, REG_EXPAND_SZ
            ' copy everything but the trailing null char
            resString = Space$(length - 1)
            CopyMemory ByVal resString, resBinary(0), length - 1
            GetRegistryValue = resString
        Case REG_BINARY
            ' resize the result resBinary
            If length <> UBound(resBinary) + 1 Then
                ReDim Preserve resBinary(0 To length - 1) As Byte
            End If
            GetRegistryValue = resBinary()
        Case REG_MULTI_SZ
            ' copy everything but the 2 trailing null chars
            resString = Space$(length - 2)
            CopyMemory ByVal resString, resBinary(0), length - 2
            GetRegistryValue = resString
        Case Else
            RegCloseKey handle
            Err.Raise 1001, , "Unsupported value type"
    End Select
   
    ' close the registry key
    RegCloseKey handle
End Function

http://www.vb2themax.com/Item.asp?PageID=CodeBank&ID=238
Complete registry control:
http://www.vbaccelerator.com/home/VB/Code/Libraries/Registry_and_Ini_Files/Complete_Registry_Control/article.asp
0
 

Expert Comment

by:RonPierce
ID: 9829882
The posting from dhaest on reading the registry in VB is the ONLY one I have found that actually works!  SO, I am curious as to why it is necessary to Dim a Byte array as  the receiving area for the registry key? It DOES seem to be necessary, for if I specify a String variable (adequately sized by Stringvar = String(1024,0) for example), the call to RegQueryValueEx  fails in my WORD/VBA macro (Office 2000), crashing WORD every time ("An error log has been created" --- sez Windows 2000, but it's nowhere to be found, of course; Win98 indicates an invalid operation, suggesting a write-protection fault).   In my case, I know that the key value is a REG_SZ, and in fact, a call to RegQueryValueEx with a null 'lpData' returns the data type as REG_SZ  and returns the required buffer size (verified as correct, by looking at the Registry) --- BUT when I then pass the String variable as the 'lpData' --- CRASH, every time.  Why?  Clearly, there are things about the "inner" workings of VB/VBA that I do not understand.  I'm feeling very fortunate to have found this posting after days of frustration, so I would welcome an explanation as to why a String var cannot be used --- or what it takes to use one in a "acceptable" way!
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 10319713
My recommandation: answered by dhaest
0
 
LVL 37

Expert Comment

by:Harisha M G
ID: 10512050
Private Sub Form1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    Dim KeyVal As String
    KeyVal = GetSetting(Application.Name, "HKEY_LOCAL_MACHINE\SOFTWARE\XXXSOFT\", "XYZSOFT_HOME", "")
End Sub
0
 

Expert Comment

by:red_helix
ID: 10586109
I found Dhaest's code solution to be Extremely Helpful.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
parentbit challenge 3 73
mapShare challenge 13 90
silent install of security banner via msiexec command 4 75
Regular Expression Calculator Tester 2 57
This article will show, step by step, how to integrate R code into a R Sweave document
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now