January 27, 2021
Hot Topics:

The Registry - Now I've got it what can I do?

  • By John Percival
  • Send Email »
  • More Articles »
Public Function GetAllKeys( _
   hKey As Long, _
   strPath As String) As Variant
Dim lRegResult As Long
Dim lCounter As Long
Dim hCurKey As Long
Dim strBuffer As String
Dim lDataBufferSize As Long
Dim strNames() As String
Dim intZeroPos As Integer
lCounter = 0
lRegResult = RegOpenKey(hKey, strPath, hCurKey)

'initialise buffers (longest possible length=255)
lDataBufferSize = 255
strBuffer = String(lDataBufferSize, " ")
lRegResult = RegEnumKey(hCurKey, _
lCounter, strBuffer, lDataBufferSize)

If lRegResult = ERROR_SUCCESS Then

'tidy up string and save it
ReDim Preserve strNames(lCounter) As String

intZeroPos = InStr(strBuffer, Chr$(0))
If intZeroPos > 0 Then
strNames(UBound(strNames)) = Left$(strBuffer, intZeroPos - 1)
strNames(UBound(strNames)) = strBuffer
End If

lCounter = lCounter + 1
Exit Do
End If
GetAllKeys = strNames
End Function

This function works using the RegEnumKey function. You pass a number to the function and it returns the name of the sub key holding that position. These are numbered from 0, starting with the oldest, so you can get some idea of the age of keys using this API call. It initialises the buffer, and then makes the call. If the call returns ERROR_SUCCESS, there was a key at that number, but if it returns something else, there was either a problem, or all the keys have been retrieved.  It adds the retrieved name to an array, and continues. If there was an error, it exits the loop, otherwise it just keeps going.
The function returns an array of names in a variant. You would use it as follows:

Dim SubKeys As Variant
Dim KeyLoop As Integer
SubKeys = GetAllKeys(HKEY_CURRENT_USER, vbNullString)

If VarType(SubKeys) = vbArray + vbString Then
For KeyLoop = 0 To UBound(SubKeys)
Debug.Print SubKeys(KeyLoop)
End If

Page 2 of 5

This article was originally published on November 20, 2002

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

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