我用win32 api来访问注册表,读取某键值的数值。代码如下。
Private Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA" (ByVal hKey As Long, ByVal lpSubKey As String, phkResult 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 Sub Command1_Click()
Dim hKey As Long, ret As Long, lenData As Long, typeData As Long
Dim Name As String
Name = "ccenter"
ret = RegCreateKey(HKEY_LOCAL_MACHINE, "Software\Microsoft\Windows\CurrentVersion\Run", hKey)
If ret = 0 Then
ret = RegQueryValueEx(hKey, Name, 0, typeData, ByVal vbNullString, lenData)
End If
End Sub
此键值是存在的,但每次运行程序,ret都等于6,是什么原因

解决方案 »

  1.   

    0表示成功,其他任何值都表示一个错误代码。If the function succeeds, the return value is ERROR_SUCCESS.If the function fails, the return value is a nonzero error code defined in WINERROR.H. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.可以到WINERROR.H这个文件里面去看看,装了visual studio都可以找到。
    好复杂。最好试试下面的FormatMessage 的api'Create a new project and add this code to Form1
    Const FORMAT_MESSAGE_ALLOCATE_BUFFER = &H100
    Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000
    Const LANG_NEUTRAL = &H0
    Const SUBLANG_DEFAULT = &H1
    Const ERROR_BAD_USERNAME = 2202&
    Private Declare Function GetLastError Lib "kernel32" () As Long
    Private Declare Sub SetLastError Lib "kernel32" (ByVal dwErrCode As Long)
    Private Declare Function FormatMessage Lib "kernel32" Alias "FormatMessageA" (ByVal dwFlags As Long, lpSource As Any, ByVal dwMessageId As Long, ByVal dwLanguageId As Long, ByVal lpBuffer As String, ByVal nSize As Long, Arguments As Long) As Long
    Private Sub Form_Load()
        Dim Buffer As String
        'Create a string buffer
        Buffer = Space(200)
        'Set the error number
        SetLastError ERROR_BAD_USERNAME
        'Format the message string
        FormatMessage FORMAT_MESSAGE_FROM_SYSTEM, ByVal 0&, GetLastError, LANG_NEUTRAL, Buffer, 200, ByVal 0&
        'Show the message
        MsgBox Buffer
    End Sub
      

  2.   

    我试了试,错误代码中文是   "指定的用户名无效"其实是你的
    Private Const HKEY_LOCAL_MACHINE = &H80000002没有设定,设定了就没问题了。
      

  3.   

    对,谢谢。另外我写了个读注册表键值的程序。
     Dim hKey As Long, ret As Long, lenData As Long, typeData As Long
       Dim Name As String
       Name = "ding"
       ret = RegOpenKey(HKEY_LOCAL_MACHINE, "HARDWARE", hKey)
        If ret = 0 Then
           ret = RegQueryValueEx(hKey, Name, 0, typeData, ByVal vbNullString, lenData)
        S = String(lenData, Chr(0))
        RegQueryValueEx hKey, Name, 0, typeData, ByVal S, lenData '×¢ÒâByValǧÍò±ðÍüÁË
        S = Left(S, InStr(S, Chr(0)) - 1)
        ret = RegCloseKey(hKey)
        End If编译没问题(声明我省略了),运行后,lendata是正确的,但s总是空的,为什么不是我要取的数据压?