VB 通过API访问 Windows 注册表

2008-04-09 04:41:00来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

  你希望你的程序能访问 Windows 注册表吗?当然,能访问庞大的 Windows 注册表是每个程序设计者都希望的事情,那么我就告诉你如何通过API函数访问 Windows 注册表吧。请先看看下面的 Visual Basic 程序:

  '根键常数

  Const HKEY_CLASSES_ROOT = -2147483648#

  Const HKEY_CURRENT_USER = -2147483647#

  Const HKEY_LOCAL_MACHINE = -2147483646#

  Const HKEY_USERS = -2147483645#

  '键值类型

  Const REG_SZ = 1& '字符串值

  Const REG_BINARY = 3& '二进制值

  Const REG_DWORD = 4& 'DWORD 值

  '声明有关API函数

  Private Declare Function RegCreateKey Lib "advapi32.dll" Alias "RegCreateKeyA" _

    ( _

     ByVal hKey As Long, _

     ByVal lpSubKey As String, _

     ByRef phkResult As Long _

     ) As Long '建立一个新的主键

  Private Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA" _

    ( _

     ByVal hKey As Long, _

     ByVal lpSubKey As String, _

     ByRef phkResult As Long _

    ) As Long '打开一个主键

  Private Declare Function RegDeleteKey Lib "advapi32.dll" Alias "RegDeleteKeyA" _

   ( _

    ByVal hKey As Long, _

    ByVal lpSubKey As String _

   ) As Long '删除一个主键

  Private Declare Function RegCloseKey Lib "advapi32.dll" _

   ( _

    ByVal hKey As Long _

   ) As Long '关闭一个主键

  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, _

    ByVal lpData As Any, _

    ByVal cbData As Long _

   ) As Long '创建或改变一个键值,lpData应由缺省的ByRef型改为ByVal型

  Private Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" _

   ( _

    ByVal hKey As Long, _

    ByVal lpValueName As String, _

    ByVal lpReserved As Long, _

    ByRef lpType As Long, _

    ByVal lpData As Any, _

    ByRef lpcbData As Long _

   ) As Long '查询一个键值,lpData应由缺省的ByRef型改为ByVal型

  Private Declare Function RegDeleteValue Lib "advapi32.dll" Alias "RegDeleteValueA" _

   ( _

    ByVal hKey As Long, _

    ByVal lpValueName As String _

    ) As Long '删除一个键值

  '主过程

  Sub Main()

   Dim nKeyHandle As Long, nValueType As Long, nLength As Long

   Dim sValue As String

   sValue = "I am a winner!"

   Call RegCreateKey(HKEY_CURRENT_USER, "New Registry Key", nKeyHandle)

   Call RegSetValueEx(nKeyHandle, "My Value", 0, REG_SZ, sValue, 255)

   sValue = Space(255)

   nLength = 255

   Call RegQueryValueEx(nKeyHandle, "My Value", 0, nValueType, sValue, nLength)

   MsgBox sValue

   Call RegDeleteValue(nKeyHandle, "My Value")

   Call RegDeleteKey(HKEY_CURRENT_USER, "New Registry Key")

   Call RegCloseKey(nKeyHandle)

  End Sub

  来看看程序运行的结果:

  在注册表的 HKEY_CURRENT_USER 根键中多了一个 New Registry Key 主键。其中除有一个空的“(默认)”值外,还有一个值为“I am a winner!”的“My Value”值。
156

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:VB5.0 设计适应显示属性的界面

下一篇:多客户环境下VB数据库编程之(9)