| 网站首页 | VB.Net实例分析 | .Net技术文摘 | 下载中心 | VB.Net书籍笔记 | .Net源码 | VBS脚本与组件调用 | Windows2008技术文摘 | 给我们留言 | 
最新公告:

  没有公告

您现在的位置: 乐博网 >> VB.Net实例分析 >> 注册表编程 >> 实例分析正文
最新推荐 更多内容
VB.Net注册表编程的实例[Dream]
VB.Net注册表编程的实例[Dream]
作者:dreamincode    来源:dreamincode     更新时间:2009-9-2
vb.net注册表编程的入门文章,当你不熟悉注册表编程时,你可能会觉得注册表很深奥,但如果你尝试过1次实例并运行成功,你会发现原来注册表编程挺容易的入手的。
NOTE: Manipulating the Windows Registry can have serious adverse affects on your computer. It is always a good idea to backup your registry before making any changes, that way if you do something wrong you have the original to fall back on. To backup your registry follow these steps:
  • 点击 Start  按钮
  • 选择 Run
  • 输入regedit 按回车打开注册表
  • When Regedit opens click on File
  • Then select Export
  • When the Save As dialog opens select where you'd like to save and give it a name
  • Under Export Range select the All radio button
  • Then click Save
乐博网提示:以上操作就是打开在dos命令行下运行regedit打开注册表,  导出注册表为一个文件 , 比如保存为lob.reg文件。
Your Registry is now saved (depending on the size of your registry exporting it can take a couple minutes). Before we jump into working with the Windows Registry, lets take a look at what exactly the Windows Registry is and what it consists of.

The Windows Registry is a repository for a computers configuration, it contains information such as:
  • Profiles for each user
  • All programs installed on the computer, and their configuration
  • Property settings for things like icons, folders, programs to start when Windows start, etc.
  • All hardware in the computer
  • All ports and what programs/hardware are using them

The Windows Registry is a hierarchal tree, it consists of Keys, Sub Keys, Predefined Keys, Hives, and Value Entries. Lets take a look at each of these items:
  • Key: A key is a node in the Registry Tree, for example SOFTWARE is a Key of HKEY_LOCAL_MACHINE
  • Sub Key: A Sub Key is a Key within a Key, for example Microsoft is a SubKey of SOFTWARE
  • Predefined Keys: A Key that represents one of the main sections of the Registry.

    There are 5 Predefined Keys in the Windows Registry

    • HKEY_CURRENT_USER : Contains the configuration for the currently logged on user
    • HKEY_USERS: Contains all loaded user profiles on the computer
    • HKEY_CLASSES_ROOT: Stores all information necessary to make sure that the correct program executes when you open a file in Windows Explorer
    • HKEY_LOCAL_MACHINE: Contains all configuration information for the computer
    • HKEY_CURRENT_CONFIG: Contains all the configuration information for the computer for the currently logged in user

  • Hive: A group of keys, sub keys and values in the registry. The 5 Predefined keys are each a Registry Hive
  • Value Entries: The value of the sub key in each key

Now that we have a high-level overview of what the registry is, what it contains and it's primary function, lets take a look at some code to manipulate, read from, and write to the Windows Registry. To facilitate working with the Windows Registry I created a Wrapper Class, so I didn't have to retype the same code over and over whenever I needed to work with the Registry. That way all I have to do is add a reference to the DLL and use it in any application I need to (even a C# application).

Before any of these methods will work you will need to add a reference to the Microsoft.Win32 Namespace. To do this add the following line at the top of your class (by the way, this is a Class Library Project, not a Windows Application project)

CODE

Imports Microsoft.Win32


The first thing to learn about working with the Windows Registry is to read information from the registry, the following method allows us to do this.

CODE

''' <summary>
'''
Function to read a value from the Registry
''' </summary>
'''
<param name="MainKey">RegistryKey -> One of the 6 main level keys you want to write to</param>
''' <param name="sKey">String -> Sub key you want to read</
param>
''' <param name="sKeyName">String -> Name of the value you want to read</param>
'''
<param name="oNameValue">Object -> The value to be read</param>
''' <returns>True (Succeeded)/
False (Failed)</returns>
''' <remarks>Created 23JUN05 -> Richard L. McCutchen</
remarks>
Public Function ReadRegistryValue(ByVal MainKey As RegistryKey, ByVal sKey As String, ByVal sKeyName As String, _
                                 
ByRef oNameValue As Object) As String
   
Dim rkKey As RegistryKey
   
Dim Value As New String("")
   
Try
     
'open the given subkey
      rkKey = MainKey.OpenSubKey(sKey, True)
      '
check to see if the subkey exists
     
If rkKey Is Nothing Then 'it doesnt exist
         '
throw an exception
         
Throw New Exception("The Registry SubKey provided doesnt exist!")
     
End If
     
'get the value
      oNameValue = rkKey.GetValue(sKeyName)
      Value = oNameValue.ToString
   Catch e As Exception
      MessageBox.Show(ex.Message, "Error: Reading Registry Value", MessageBoxButtons.OK, MessageBoxIcon.Error)
   End Try
   Return Value
End Function


The next thing you'll want to investigate is writing a value to the Registry, this comes in handy in application installations, you could even use it to store user information. For writing to the Registry I have 2 functions:
  • Create a registry Sub Key
  • Create a Sub key Value Entry

First you need to create a Sub Key before you can add Value Entries to it

CODE

''' <summary>
'''
Function to create a new Sub Key in the Windows Registry
''' </summary>
'''
<param name="MainKey">RegistryKey -> One of the 6 main keys to create the subkey in</param>
''' <param name="sKey">String -> Name of the subkey to create</
param>
''' <param name="KeyPermissions">RegistryKepPermissionCheck -> Specifies permissions of the SubKey to be created</param>
'''
<returns>True (Succeeded)/False (Failed)</returns>
''' <remarks>Created 23JUN05 -> Richard L. McCutchen</
remarks>
Public Function CreateRegistrySubKey(ByVal MainKey As RegistryKey, ByVal sKey As String, _
   
ByVal KeyPermissions As RegistryKeyPermissionCheck) As Boolean
   
Try
     
'create the new subkey
      MainKey.CreateSubKey(sKey, KeyPermissions)
      Return True
   Catch ex As Exception
      MessageBox.Show(ex.Message, "Error: Creating SubKey", MessageBoxButtons.OK, MessageBoxIcon.Error)
      Return False
   End Try
End Function


Now that you've created your Sub Key you can add Value Entries to it using this function.

CODE

''' <summary>
'''
Writes a value in the Registry
''' </summary>
'''
<param name="MainKey">RegistryKey -> One of the 6 main keys that you want to write to</param>
''' <param name="sKey">String -> Name of the subkey you want to write to. If the subkey doesnt
''' exist it will be created</
param>
''' <param name="sKeyName">String -> Name of the value to create</param>
'''
<param name="oNameValue">Object -> Value to be stored</param>
''' <param name="RegType">RegistryValueKind -> Data type of the subkey value</
param>
''' <returns>True (Succeedeed)/False (Failed)</returns>
'''
<remarks>Created 23JUN05 -> Richard L. McCutchen</remarks>
Public Function WriteSubKeyValue(ByVal MainKey As RegistryKey, ByVal sKey As String, ByVal sKeyName As String, _
                                   ByVal oNameValue As Object, ByVal RegType As RegistryValueKind) As Boolean
   Dim rkKey As RegistryKey
   Try
      'Open the given subkey
      rkKey = MainKey.OpenSubKey(sKey, True)
      'check to see if the subkey exists
      If rkKey Is Nothing Then 'doesnt exist
         'create the subkey
         rkKey = MainKey.CreateSubKey(sKey, RegistryKeyPermissionCheck.Default)
      End If
      'set the value of the subkey
      rkKey.SetValue(sKeyName, oNameValue, RegType)
      Return True
   Catch ex As Exception
      MessageBox.Show(ex.Message, "Error: Writing Registry Value", MessageBoxButtons.OK, MessageBoxIcon.Error)
      Return False
   End Try
End Function


The next aspect of working with the Registry is removing values from the Registry (be careful with this, you really shouldn't be removing values that aren't associated with your application unless you know what you are doing).

This wrapper has 2 delete function:
  • Delete a SubKey value
  • Delete the SubKey itself

First lets take a look at deleting a Sub Key value. Pass it the Predefined Key, the Sub Key and the Value Entry you want to remove and it removes it for you. If you provide a Sub Key that doesn't exist it displays this error to you.

CODE

''' <summary>
'''
Function to delete a subkey value from the Windows Registry
''' </summary>
'''
<param name="MainKey">RegistryKey -> One of the 6 main keys you want to delete from</param>
''' <param name="sKey">String -> Name of the SubKey you want to delete a value from</
param>
''' <param name="sKeyName">String -> Name of the value to delete</param>
'''
<returns>True (Succeeded)/False (Failed)</returns>
''' <remarks>Created 23JUN05 -> Richard L. McCutchen</
remarks>
Public Function DeleteSubKeyValue(ByVal MainKey As RegistryKey, ByVal sKey As String, ByVal sKeyName As String) As Boolean
   
Dim rkKey As RegistryKey
   
Try
     
'open the given subkey
      rkKey = MainKey.OpenSubKey(sKey, True)
      '
check to make sure the subkey exists
     
If Not sKey Is Nothing Then 'subkey exists
         '
delete the subkey
         
MainKey.DeleteValue(sKeyName, True)
         
Return True
     
Else    'subkey doesnt exist
         '
throw an exception
         
Throw New Exception("The SubKey provided doesnt exist! Please check your entry and try again")
         
Return False
     
End If
   
Catch ex As Exception
     
MessageBox.Show(ex.Message, "Error: Deleting SubKey Value", MessageBoxButtons.OK, MessageBoxIcon.Error)
     
Return False
   
End Try
End Function


The next function deletes the Sub Key itself. Remember, when you delete a Sub Key all the Value Entries it contained are deleted as well.

CODE

''' <summary>
'''
Function to delete a SubKey from the Windows Registry
''' </summary>
'''
<param name="MainKey">RegistryKey -> One of the top main keys to delete from</param>
''' <param name="sKey">String -> Name of the SubKey to delete</
param>
''' <returns>True (Succeeded)/False (Failed)</returns>
'''
<remarks>Created 23JUN05 -> Richard L. McCutchen</remarks>
Public Function DeleteRegistrySubKey(ByVal MainKey As RegistryKey, ByVal sKey As String) As Boolean
   Dim rkKey As RegistryKey
   Try
      'open the given subkey
      rkKey = MainKey.OpenSubKey(sKey, True)
      'check to make sure the subkey exists
      If Not sKey Is Nothing Then 'subkey exists
         MainKey.DeleteSubKey(sKey, True)
         Return True
      Else    'subkey doesnt exist
         'throw an exception letting the user know
         Throw New Exception("The SubKey provided doesn't exist. Please check your entry and try again.")
         Return False
      End If
   Catch ex As Exception
      MessageBox.Show(ex.Message, "Error: Deleting SubKey", MessageBoxButtons.OK, MessageBoxIcon.Error)
      Return False
   End Try
End Function


There you have it, a wrapper class for working with the Windows Registry. It is much easier than expected in .Net, I can remember working with the Windows Registry in VB6 and it was, to say the least, a nightmare. .Net made a programmers life some much easier.

I am providing both the source code and the DLL for this wrapper class, it is under a GNU General Public License so I request you leave the License Header in place. With the GNU General Public License you are free to modify this code, all I ask is if you use this wrapper in production is a reference to the author (me)
  • 上一篇:

  • 下一篇: 没有了
  • 【字体: 】【打印此文】【关闭窗口
      相关文章:(只显示最新16条)
    VB.Net注册表中读取值的实例
    注册表结构分析与vb.net编程的结合
    VB.Net注册表权限编程的分析[乐博网原创]
    Registry.LocalMachine属性的实例
    RegistryKey.OpenRemoteBaseKey方法的实例
    Registry.Users属性的实例
    staticGetValue和SetValue操作注册表实例
    RegistryKey.OpenSubKey打开注册表键值实例
    VB.Net注册表键值类型的分析[乐博网原创]
    VB.Net从注册表读取Excel版本信息
    VB.Net操作注册表实例
    VB.NET注册表编程实例

    | 设为首页 | 加入收藏 | 联系站长 | | 友情链接 | 版权申明 |
    乐博网欢迎各种媒体转载我们的原创作品[转载请注明出处];我们鼓励更多VB.Net开发者一起加入研究与探讨;如发现文章访问错误、内容错误或版权疑问、内容有违相关法律(如涉及政治、色情、反动或散布虚假有害信息)等情况,请及时向我们举报,我们将及时纠正!
    联系邮箱:Shiny#vip.qq.com (#替换为@) QQ交流群: 40797788 [闽ICP备05014267号]