dcsimg
December 9, 2016
Hot Topics:

Accessing the Windows Registry with the API

  • November 19, 2002
  • By John Percival
  • Send Email »
  • More Articles »
Public Function GetSettingString( _
            hKey As Long, _
            strPath As String, _
            strValue As String, _
            Optional _
      Default As String) As String
Dim hCurKey As Long
Dim lResult As Long
Dim lValueType As Long
Dim strBuffer As String
Dim lDataBufferSize As Long
Dim intZeroPos As Integer
Dim lRegResult As Long

' Set up default value
If Not IsEmpty(Default) Then
GetSettingString = Default
Else
GetSettingString = ""
End If

lRegResult = RegOpenKey(hKey, _
                        strPath, hCurKey)
lRegResult = RegQueryValueEx(hCurKey, _
                    strValue, 0&, _
                    lValueType, ByVal 0&, _
                    lDataBufferSize)

If lRegResult = ERROR_SUCCESS Then

If lValueType = REG_SZ Then

strBuffer = String(lDataBufferSize, " ")
lResult = RegQueryValueEx(hCurKey, _
                          strValue, 0&, 0&, _
                          ByVal strBuffer, _
                          lDataBufferSize)

intZeroPos = InStr(strBuffer, Chr$(0))
If intZeroPos > 0 Then
GetSettingString = Left$(strBuffer, _
                         intZeroPos - 1)
Else
GetSettingString = strBuffer
End If

End If

Else
' there is a problem
End If

lRegResult = RegCloseKey(hCurKey)
End Function
Public Sub SaveSettingString(hKey As Long, strPath _
As String, strValue As String, strData As String)
Dim hCurKey As Long
Dim lRegResult As Long

lRegResult = RegCreateKey(hKey, strPath, hCurKey)

lRegResult = RegSetValueEx(hCurKey, strValue, 0, REG_SZ, _
ByVal strData, Len(strData))

If lRegResult <> ERROR_SUCCESS Then
'there is a problem
End If

lRegResult = RegCloseKey(hCurKey)
End Sub

These Registry functions for strings are quite complicated because of the need to initialise buffers. The function to retrieve strings first sets up the default value. This will be used if the specified key is not valid. The first call to RegQueryValueEx determines the data type in the key and the length if it is a string. The second call retrieves the string. Then the string is processed, removing any trailing nulls.

The function to save the string is much simpler. The RegSetValueEx function is called, passing the type as a string, the string data, and the length of the string.





Page 4 of 6



Comment and Contribute

 


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

 

 


Enterprise Development Update

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

Sitemap | Contact Us

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