65.9K
CodeProject 正在变化。 阅读更多。
Home

如何编写 Windows 注册表程序

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.31/5 (57投票s)

2008年4月14日

CPOL

1分钟阅读

viewsIcon

53782

downloadIcon

1011

本文将指导您如何创建/检索/删除 Windows 注册表中的键值。

引言

本文将指导您如何使用 Windows 注册表存储用户特定的非关键数据,这些数据可以在应用程序之间检索。

背景

注册表被划分为许多逻辑部分,更常被称为 hives(配置单元)。注册表配置单元是键、子键和值的集合。在为应用程序编程时,我们需要存储应用程序特定的数据。这些数据通常存储在 HKEY_CURRENT_USER 配置单元的 ‘software’ 子树中,或者HKEY_CURRENT_USER\Software。该配置单元的支持文件位于 %SystemRoot%\Profiles\Username 文件夹中。而所有其他配置单元的支持文件位于 %SystemRoot%\System32\Config 文件夹中。

Using the Code

要在 VB.NET 中使用注册表,首先需要导入 Microsoft.Win32 命名空间。这将提供对 RegistryKey 类的访问权限。

创建注册表键

'Create a SubKey under Software subtree of HKEY_CURRENT_USER hive.	
Dim vRegistryKey As RegistryKey
vRegistryKey = Registry.LocalMachine.OpenSubKey("Software", True)
vRegistryKey.CreateSubKey("NewKey")
vRegistryKey.Close()

'Open Newly created SubKey and insert values using SetValue() method.	
Dim vRegistryKey1 As RegistryKey
vRegistryKey1 = Registry.LocalMachine.OpenSubKey("Software\NewKey", True)
vRegistryKey1.SetValue("Key Name", txtKeyName.Text)
vRegistryKey1.SetValue("Key Description", txtKeyDescription.Text)
vRegistryKey1.Close()

检索现有注册表键

'Open required SubKey and use GetValue() method to fetch key values.	
Dim vRegistryKey As RegistryKey
vRegistryKey = Registry.LocalMachine.OpenSubKey("Software\NewKey", True)
txtKeyName.Text = vRegistryKey.GetValue("Key Name").ToString
txtKeyDescription.Text = vRegistryKey.GetValue("Key Description").ToString
vRegistryKey.Close()

删除现有注册表键

'Open required SubKey and use DeleteSubKey() method to delete subkey.	
Dim vRegistryKey As RegistryKey
vRegistryKey = Registry.LocalMachine.OpenSubKey("Software", True)
vRegistryKey.DeleteSubKey("NewKey")
vRegistryKey.Close()

注意事项

在提供的下载示例中,当您创建一项时,请输入有效的服务器/IP 地址(您可以输入 'localhost'),否则将显示错误。

结束语

希望本文对您在注册表键编程方面有所帮助。有关更多信息,您可以查看下载部分中提供的演示程序,或通过 arshad@cherisys.com 与我联系。

祝您好运!

© . All rights reserved.