Accessing the Windows Registry with the API
Public Function GetSettingLong( _ ByVal hKey As Long, _ ByVal strPath As String, _ ByVal strValue As String, _ Optional Default As Long) As Long Dim lRegResult As Long Dim lValueType As Long Dim lBuffer As Long Dim lDataBufferSize As Long Dim hCurKey As Long ' Set up default value If Not IsEmpty(Default) Then GetSettingLong = Default Else GetSettingLong = 0 End If lRegResult = RegOpenKey(hKey, _ strPath, hCurKey) lDataBufferSize = 4 ' 4 bytes = 32 bits = long lRegResult = RegQueryValueEx(hCurKey, _ strValue, 0&, _ lValueType, lBuffer, _ lDataBufferSize) If lRegResult = ERROR_SUCCESS Then If lValueType = REG_DWORD Then GetSettingLong = lBuffer End If Else 'there is a problem End If lRegResult = RegCloseKey(hCurKey) End Function Public Sub SaveSettingLong(ByVal hKey As Long, ByVal _ strPath As String, ByVal strValue As String, ByVal _ lData As Long) Dim hCurKey As Long Dim lRegResult As Long lRegResult = RegCreateKey(hKey, strPath, hCurKey) lRegResult = RegSetValueEx(hCurKey, strValue, 0&, _ REG_DWORD, lData, 4) If lRegResult <> ERROR_SUCCESS Then 'there is a problem End If lRegResult = RegCloseKey(hCurKey) End Sub
These two functions are probably the simplest of the three data types. We know the length of data that we want to retrieve so we don't need any extra calls.
Public Function GetSettingLong(ByVal hKey As Long, _ ByVal strPath As String, ByVal strValue As String, _ Optional Default As Long) As Long Dim lRegResult As Long Dim lValueType As Long Dim lBuffer As Long Dim lDataBufferSize As Long Dim hCurKey As Long ' Set up default value If Not IsEmpty(Default) Then GetSettingLong = Default Else GetSettingLong = 0 End If lRegResult = RegOpenKey(hKey, strPath, hCurKey) lDataBufferSize = 4 ' 4 bytes = 32 bits = long lRegResult = RegQueryValueEx(hCurKey, strValue, 0&, _ lValueType, lBuffer, lDataBufferSize) If lRegResult = ERROR_SUCCESS Then If lValueType = REG_DWORD Then GetSettingLong = lBuffer End If Else 'there is a problem End If lRegResult = RegCloseKey(hCurKey) End Function Public Sub SaveSettingLong(ByVal hKey As Long, ByVal _ strPath As String, ByVal strValue As String, ByVal lData As Long) Dim hCurKey As Long Dim lRegResult As Long lRegResult = RegCreateKey(hKey, strPath, hCurKey) lRegResult = RegSetValueEx(hCurKey, strValue, 0&, _ REG_DWORD, lData, 4) If lRegResult <> ERROR_SUCCESS Then 'there is a problem End If lRegResult = RegCloseKey(hCurKey) End Sub
Page 5 of 6
This article was originally published on November 20, 2002