帮我看看这段代码还可以精简些吗^-^
Option Explicit
Public Const REG_SZ = 1 ' Unicode nul terminated string
Public Const REG_BINARY = 3 ' Free form binary
Public Const HKEY_CURRENT_USER = &H80000001
Public Const HKEY_LOCAL_MACHINE = &H80000002
Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA" (ByVal hkey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hkey As Long) As Long
Declare Function RegCreateKey Lib "advapi32.dll" Alias "RegCreateKeyA" (ByVal hkey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
Declare Function RegDeleteValue Lib "advapi32.dll" Alias "RegDeleteValueA" (ByVal hkey As Long, ByVal lpValueName As String) As Long
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
Declare Function RegSetValueEx Lib "advapi32.dll" Alias "RegSetValueExA" (ByVal hkey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long, lpData As Any, ByVal cbData As Long) As Long
Dim hkey As Long
Dim lResult As Long, lValueType As Long, strBuf As String, lDataBufSize As Long
Function GetStringValue(ByVal MainKeyHandle As Long, ByVal Subkey As String, strValueName As String)
'Get string value from reg
lResult = RegOpenKey(MainKeyHandle, Subkey, hkey) 'open the key
If lResult <> 0 Then GetStringValue = "?": RegCloseKey hkey: Exit Function 'if the key not exists
'Get information about the key
lResult = RegQueryValueEx(hkey, strValueName, 0, lValueType, ByVal 0, lDataBufSize)
If lResult = 0 And lValueType = REG_SZ Then
strBuf = String(lDataBufSize, Chr(0)) 'Create a buffer
'retrieve the key's content
lResult = RegQueryValueEx(hkey, strValueName, 0, 0, ByVal strBuf, lDataBufSize)
If lResult = 0 Then
'Remove the unnecessary chr(0)'s
GetStringValue = Left(strBuf, InStr(1, strBuf, Chr(0)) - 1)
Else
GetStringValue = "?"
End If
Else
GetStringValue = "?"
End If
RegCloseKey hkey
End Function
这里用了两次RegQueryValueEx,若第一次返回成功,第二次是否一定成功
若一定成功,
If lResult = 0 Then
'Remove the unnecessary chr(0)'s
GetStringValue = Left(strBuf, InStr(1, strBuf, Chr(0)) - 1)
Else
GetStringValue = "?"
End If
这段就变成一行了:GetStringValue = Left(strBuf, InStr(1, strBuf, Chr(0)) - 1)