VBGood网站全文搜索 Google

搜索VBGood全站网页(全文搜索)
首页 - 经验之谈 - 用VB操作注册表(五)
发表评论(0)作者:梦里水乡, 平台:VB6.0+Win98, 阅读:12761, 日期:2001-02-13
用VB操作注册表(五)
梦里水乡

登录数据库Registry的Value的存取--写入某个Key指定名称的值

要完成Value的写入,需要用到API函数RegSetValueEx。下面是它的一些说明。
VB声明
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
参数:
hKey:Key Handle
lpValueName:Value名称
Reserved:保留参数,具体使用时置为0即可
dwType:数据类型
lpData:所设置的数据,注意这一参数被定义成lpData As Any,所以要传入字符串数据时别忘了在参数前加保留字ByVal
cbData:数据的长度。注意:如果写入的数据属于REG_SZ、REG_EXPAND_SZ、REG_MULTI_SZ类型时,则这个长度应该包含chr(0)字符。
返回值: =0,表示成功;≠0,表示失败。

由于RegSetValueEx的参数和RegQueryValueEx完全一样,他们的使用方式也差不多,因此,在这里我只是举出下面的例子来简略地说一下就行。
`下面的例子在HKEY_CURRENT_USER\Software\SetValue下建立
`Default Value-->REG_SZ "VB操作注册表"
`str1 -->REG_SZ "我爱我的祖国"
`str2 -->REG_EXPAND_SZ "%WinDir%Command"
`str3 -->REG_MULTI_SZ "hongqt" + Chr(0) + "lstc" + Chr(0) + "edu" + Chr(0) + "cn" + Chr(0) + Chr(0)
`LongData -->REG_DWORD 99999
`BinaryData -->REG_BINARY 11,22,33,44,aa,bb,cc,dd


`*******************setvalue.bas ************************

Option Explicit
Public Const HKEY_CLASSES_ROOT = &H80000000
Public Const HKEY_CURRENT_USER = &H80000001
Public Const HKEY_LOCAL_MACHINE = &H80000002
Public Const HKEY_USERS = &H80000003
Public Const HKEY_PERFORMANCE_DATA = &H80000004
Public Const HKEY_CURRENT_CONFIG = &H80000005
Public Const HKEY_DYN_DATA = &H80000006

Public Const REG_NONE = 0
Public Const REG_SZ = 1
Public Const REG_EXPAND_SZ = 2
Public Const REG_BINARY = 3
Public Const REG_DWORD = 4
Public Const REG_DWORD_BIG_ENDIAN = 5
Public Const REG_MULTI_SZ = 7
`注意下面的函数声明要在一行内写完
Declare Function RegCreateKey Lib "advapi32.dll" Alias "RegCreateKeyA" (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 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

Sub Main()
Dim hKey As Long
RegCreateKey HKEY_CURRENT_USER, "Software\SetValue", hKey
RegSetValueEx hKey, "", 0, REG_SZ, ByVal "VB操作注册表", 13
RegSetValueEx hKey, "Str1", 0, REG_SZ, ByVal "我爱我的祖国", 13
RegSetValueEx hKey, "Str2", 0, REG_EXPAND_SZ, ByVal "%WinDir%Command", 16
Dim S As String
S = "hongqt" + Chr(0) + "lstc" + Chr(0) + "edu" + Chr(0) + "cn" + Chr(0) + Chr(0)
RegSetValueEx hKey, "Str3", 0, REG_MULTI_SZ, ByVal S, 20

Dim L As Long
L = 99999
RegSetValueEx hKey, "LongData", 0, REG_DWORD, L, 4

Dim bArr(0 To 7) As Byte
bArr(0) = &H11: bArr(1) = &H22: bArr(2) = &H33: bArr(3) = &H44
bArr(4) = &HAA: bArr(5) = &HBB: bArr(6) = &HCC: bArr(7) = &HDD
RegSetValueEx hKey, "BinaryData", 0, REG_BINARY, bArr(0), 8

MsgBox "已完成 RegSetValueEx! 请检查 HKEY_CURRENT_USER\Software\SetValue 的内容。"
RegCloseKey hKey

End Sub