VBGood网站全文搜索 Google

搜索VBGood全站网页(全文搜索)
首页 - 经验之谈 - VB修改注册表一特例
发表评论(0)作者:, 平台:, 阅读:12080, 日期:2000-04-06
VB修改注册表一特例

我们知道,在VB中调用Windows的API函数能比较方便的修改系统注目表,然而笔者近来在一次应用中偶然发现这样一个特殊的问题:若在注目表HKEY_LOCAL_MACHINE\Mircrosoft\Windows \CurrentVersion\Setup下有一双字节型串值SetupOnce为"0x7cf70b"现要通过VB把其改为"0xffffffff"(十进制为4294967295)。是不是直接定义长整型变量Updata,并赋值Updata=4294967295,然后调用API函数RegSetValueEx

("HKEY_LOCAL_MACHINE", "Software\Mircrosoft \Windows\CurrentVersion\Setup","SetupOnce",0,4,Updata,4)就能达到目的呢?实际非也!这样操作,将会出错,出错报告为"实时错误6,溢出"。问题出在那里呢?笔者经过思考,发现十六进制0xffffffff化为十进制4294967295共十位数,显然把变量Updata在定义为长整型时存在错误。知道了问题所在,我们把Updata变量重新定义为双精度型,接下来的问题是Updata到底应赋予何值?我们可以采用反推法,即先在注册表中先令SetupOnce为"0xffffffff",在VB中定义变量Updata(double型),调用API中注册表查询库函数RegQueryValueEx("HKEY_LOCAL_MACHINE","Software\Mircrosoft\Windows \CurrentVersion \Setup","SetupOnce",0,4,Updata,4)在VB中一调试,结果出来了,Up!data的值为2.12199579047121E-314(这个数字真有点吓人)。知道了Updata的取值我们就可以用RegSetValueEx函数修改原来

SetupOnce的值了。下面给出以上所述过程的一个例程,希望对您有所启发。

  新建一工程,在此工程声明段声明常量及API库函数:

PrivateDeclareFunction RegCloseKey Lib "advapi32.dll" (ByVal hKey AsLong)As Long

Private Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey AsString, ByVal ulOptions As Long, ByVal samDesired As Long,phkresult As Long) As Long

Private Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" (ByVal hKey As Long,ByVal lpValueNameAs String, ByVal lpReserved As Long,lpType As Long, lpDataAs Any, lpcbData As Long) As Long


'Note that if you declarethe lpData parameter as String, youmust pass it By Value.


Private Declare Function RegSetValueEx Lib "advapi32.dll" Alias "RegSetValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long,lpDataAs Any, ByVal cbData As Long) As Long


'Note that ifyou declarethe lpData parameter as String, you must pass itBy Value.


Const HKEY_LOCAL_MACHINE = &H80000002 Const REG_DWORD =4 Const ERROR_SUCCESS = 0& Const KEY_ALL_ACCESS = &H3F ConstA = 2.12199579047121E-314 Const reg1 = "software \microsoft\windows \currentversion\setup"Public phkresult As Long


在Form的Click事件中添加以下代码:

Private Sub Form_Click() Dim back As Long Dim Updata As Double back = RegOpenKeyEx(HKEY_LOCAL_MACHINE, reg1, 0&,KEY_ALL_ACCESS,phkresult) back = RegQueryValueEx(phkresult,"SetupOnce", 0,REG_DWORD, Updata, 4)


'如果要用RegQueryValueEx()读出某一值,函数调用前必须以KEY_QUERY_VALUE参数形式打开,实例中以KEY_ALL_ACCESS参数打开,实际上已包含了KEY_QUERY_VALUE。


If back = ERROR_SUCCESS Then If Updata <> A Then Updata = A back = RegSetValueEx (phkresult, "SetupOnce", 0&,REG_DWORD,Updata, 4) If back = ERROR_SUCCESS Then

MsgBox "标记成功!"Else MsgBox "标记不成功!"

Exit Sub

End If

Else MsgBox "要标记的项已是所需" RegCloseKey(phkresult)

Exit Sub

End If

Else Msgbox "注册表中无所需修改的项" End If RegCloseKey(phkresult)

End Sub

其实,以上例程完全可以用做加密技术。国内某个带"霸"字的软件亦采用了类似的加密技术,当然,只是在加密的表现结果上表现而已。