Recipe 14.20. Accessing the Registry


Problem

You wish to read or write keys and values in one of the registry hives.

Solution

Sample code folder: Chapter 14\RegistryAccess

Use the My.Computer.Registry object and its members to access and update portions of the registry.

Discussion

This recipe's source code implements a read-only (and highly simplified) version of the Windows RegEdit application. Create a new Windows Forms application, and add the following controls to Form1:

  • A treeView control named RegistryTree.

  • A ListBox control named RegistryValues.

  • A TextBox control named ValueData. Set its Multiline property to true, its ScrollBars property to Vertical, and its ReadOnly property to TRue.

Add some informational labels if desired, and arrange the controls so the form looks like Figure 14-15.

Now add the following source code to the form's code template:

 Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load    ' ----- Load the root objects.    Dim rootNode As TreeNode    Dim childNode As TreeNode    rootNode = RegistryTree.Nodes.Add("My Computer") 

Figure 14-15. The form and controls for the registry viewer


    childNode = rootNode.Nodes.Add("HKEY_CLASSES_ROOT")    childNode.Nodes.Add("")    childNode = rootNode.Nodes.Add("HKEY_CURRENT_USER")    childNode.Nodes.Add("")    childNode = rootNode.Nodes.Add("HKEY_LOCAL_MACHINE")    childNode.Nodes.Add("")    childNode = rootNode.Nodes.Add("HKEY_USERS")    childNode.Nodes.Add("")    childNode = rootNode.Nodes.Add("HKEY_CURRENT_CONFIG")    childNode.Nodes.Add("")    rootNode.Expand( ) End Sub Private Function BuildRegistryPath( _       ByVal fromNode As TreeNode) As String    ' ----- Traverse a tree backward, building the node path.    If (fromNode.Parent Is Nothing) Then       ' ----- This is the root node.       Return "\"    Else       ' ----- This is an intermediate node.       Return BuildRegistryPath(fromNode.Parent) & _          "\" & fromNode.Text    End If End Function Private Function GetHiveFromName(ByVal hiveName As String) _       As Microsoft.Win32.  RegistryKey    ' ----- Given the name of a hive, return its key.    Select Case hiveName       Case "HKEY_CLASSES_ROOT"          Return My.Computer.Registry.ClassesRoot       Case "HKEY_CURRENT_USER"          Return My.Computer.Registry.CurrentUser       Case "HKEY_LOCAL_MACHINE"          Return My.Computer.Registry.LocalMachine       Case "HKEY_USERS"          Return My.Computer.Registry.Users       Case "HKEY_CURRENT_CONFIG"          Return My.Computer.Registry.CurrentConfig       Case Else          Return Nothing    End Select End Function Private Function GetKeyFromNode(ByVal whichNode As TreeNode) _       As Microsoft.Win32.RegistryKey    ' ----- The user is just about to expand a node. If it    '       includes a blank node, retrieve the actual    '       child nodes from the registry.    Dim registryPath As String    Dim hiveName As String    Dim registryKey As Microsoft.Win32.RegistryKey    ' ----- Access this part of the registry.    registryPath = BuildRegistryPath(whichNode).Substring(2)    If (registryPath.Contains("\") = True) Then       ' ----- Extract the hive and path parts.       hiveName = registryPath.Substring(0, _          registryPath.IndexOf("\"c))       registryPath = registryPath.Substring( _          hiveName.Length + 1)    Else       ' ----- The active node is a hive.       hiveName = registryPath       registryPath = ""    End If    ' ----- Obtain the right hive.    registryKey = GetHiveFromName(hiveName)    If (registryKey Is Nothing) Then Return Nothing    ' ----- Obtain the right subkey, if needed.    If (registryPath <> "") Then _       registryKey = registryKey.OpenSubKey(registryPath)    ' ----- This is the right key.    Return registryKey End Function Private Sub   RegistryTree_AfterSelect( _       ByVal sender As Object, ByVal e As _       System.Windows.Forms.TreeViewEventArgs) _       Handles RegistryTree.AfterSelect    ' ----- Display the values associated with a node.    Dim registryKey As Microsoft.Win32.RegistryKey    ' ----- Clear any existing data.    RegistryValues.Items.Clear( )    ValueData.Clear( )    ' ----- Ignore if this is the root node.    If (e.Node.Parent Is Nothing) Then Return    ' ----- Get the registry key associated with this    '       tree node.    registryKey = GetKeyFromNode(e.Node)    ' ----- There is always a default value.    RegistryValues.Items.Add("(Default)")    ' ----- Get all of the values of this key, and add them    '       to the list.    Me.Cursor = Cursors.WaitCursor    Try       For Each oneValue As String In _             registryKey.GetValueNames( )          RegistryValues.Items.Add(oneValue)       Next oneValue    Finally       Me.Cursor = Cursors.Arrow    End Try    registryKey.Close( ) End Sub Private Sub RegistryTree_BeforeExpand( _       ByVal sender As Object, ByVal e As _       System.Windows.Forms.TreeViewCancelEventArgs) _       Handles RegistryTree.BeforeExpand    ' ----- The user is just about to expand a node. If it    '       includes a blank node, retrieve the actual    '       child nodes from the registry.    Dim registryKey As Microsoft.Win32.RegistryKey    Dim keyNode As TreeNode    ' ----- Ignore if this node was already expanded.    If (e.Node.FirstNode.Text <> "") Then Return    e.Node.Nodes.Remove(e.Node.FirstNode)    ' ----- Get the registry key associated with this tree node.    registryKey = GetKeyFromNode(e.Node)    ' ----- Get all of the child keys of this key, and add them    '       to the tree.    Me.Cursor = Cursors.WaitCursor    Try      For Each oneKey As String In _              registryKey.GetSubKeyNames( )         keyNode = e.Node.Nodes.Add(oneKey)         keyNode.Nodes.Add("")      Next oneKey   Finally      Me.Cursor = Cursors.Arrow   End Try   registryKey.Close( ) End Sub Private Sub RegistryValues_SelectedIndexChanged( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles RegistryValues.SelectedIndexChanged    ' ----- Display the data associated with the selected list item.    Dim registryKey As Microsoft.Win32.RegistryKey    Dim actualValue As Object    Dim valueName As String    ' ----- Clear any existing data.    ValueData.Clear( )    ' ----- Ignore if nothing is active.    If (RegistryValues.SelectedIndex = _       ListBox.NoMatches) Then Return    ' ----- Ignore if this is the root node.    If (RegistryTree.SelectedNode.Parent Is Nothing) _       Then Return    ' ----- Get the registry key associated with this    ' tree node.    registryKey = GetKeyFromNode(RegistryTree.SelectedNode)    ' ----- Determine the value to retrieve.    valueName = RegistryValues.Text    If (valueName = "(Default)") Then valueName = ""    ' ----- Display the value.    actualValue = registryKey.GetValue(valueName)    If (actualValue IsNot Nothing) Then _       ValueData.Text = actualValue.ToString( )    registryKey.Close( ) End Sub 

To use the program, expand and select registry keys in the RegistryTree control, and select values in the RegistryValues control. The RegistryTree_BeforeExpand event handler loads only those branches that have been expanded, so the program doesn't have to load the entire registry at once. The program could be greatly enhanced to properly display nonstring and nonnumeric data, and to manage security-and access-related errors.

The system registry is grouped into hives, although most of the hives are simply shortcuts to specific portions of the master HKEY_CLASSES_ROOT hive. The My.Computer.Registry object provides access to these hives through the following members, each of which is an instance of Microsoft.Win32. RegistryKey:

  • ClassesRoot provides access to the HKEY_CLASSES_ROOT hive.

  • CurrentConfig provides access to the HKEY_CURRENT_CONFIG hive.

  • CurrentUser provides access to the HKEY_CURRENT_USER hive.

  • DynData provides access to the HKEY_DYNAMIC_DATA hive.

  • LocalMachine provides access to the HKEY_LOCAL_MACHINE hive.

  • PerformanceData provides access to the HKEY_PERFORMANCE_DATA hive.

  • Users provides access to the HKEY_USERS hive.

The RegistryKey class for each hive includes features that let you access the subordinate keys and values associated with that hive or key. Fortunately, any subordinate key you access can also appear as a RegistryKey instance, making it easy to traverse the registry from any hive.

This recipe's code uses the RegistryKey. OpenSubKey() method to access specific keys below a hive root. For instance, to access the key \\HKEY_CURRENT_USER\Software\Microsoft, you would make the following function call:

 Dim microsoftKey As Microsoft.Win32.RegistryKey = _    My.Computer.Registry.CurrentUser.OpenSubKey( _    "Software\Microsoft") 

Each key includes zero or more values, including a default value (which is actually named default). To retrieve a value for a key, use the key's GetValue() method, a feature also used in the sample code. The registry can store data in a variety of formats, so use the related GetValueKind() method to determine the type of data stored. To access the default value for a key, use an empty string for the value name.

To add or update a value for a key, use the RegistryKey.SetValue() method.

For both reads and writes of key and value data, the system administrator may impose access limits on certain areas of the registry. Attempting to read or write an inaccessible portion of the registry generates an exception.





Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net