PageRenderTime 11ms CodeModel.GetById 1ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 1ms

/Visual Studio 2008/VBMonitorRegistryChange/MainForm.vb

#
Visual Basic | 145 lines | 78 code | 23 blank | 44 comment | 0 complexity | 1d750de89333049e130912a7108e007a MD5 | raw file
  1'*************************** Module Header ******************************\
  2' Module Name:  MainForm.vb
  3' Project:	    VBMonitorRegistryChange
  4' Copyright (c) Microsoft Corporation.
  5' 
  6' This is the main form of this application. It is used to initialize the UI and 
  7' handle the events.
  8' 
  9' This source is subject to the Microsoft Public License.
 10' See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
 11' All other rights reserved.
 12' 
 13' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 14' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 15' WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
 16'**************************************************************************
 17
 18Imports System.Management
 19Imports Microsoft.Win32
 20
 21Partial Public Class MainForm
 22    Inherits Form
 23
 24    ' Current status
 25    Private isMonitoring As Boolean = False
 26
 27    Private watcher As RegistryWatcher = Nothing
 28
 29    Public Sub New()
 30        InitializeComponent()
 31    End Sub
 32
 33    Private Sub MainForm_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
 34
 35        ' Initialize the data source of cmbHives. Changes to the HKEY_CLASSES_ROOT 
 36        ' and HKEY_CURRENT_USER hives are not supported by RegistryEvent or classes
 37        ' derived from it, such as RegistryKeyChangeEvent.        
 38        cmbHives.DataSource = RegistryWatcher.SupportedHives
 39
 40    End Sub
 41
 42    ''' <summary>
 43    ''' Handle the click event of btnMonitor.
 44    ''' </summary>
 45    Private Sub btnMonitor_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnMonitor.Click
 46
 47        ' If this application is monitoring the registry key, then stop monitoring 
 48        ' and enable the editors.
 49        If isMonitoring Then
 50            Dim success As Boolean = StopMonitor()
 51            If success Then
 52                btnMonitor.Text = "Start Monitor"
 53                cmbHives.Enabled = True
 54                tbRegkeyPath.ReadOnly = False
 55                isMonitoring = False
 56                lstChanges.Items.Add(String.Format("{0} Stop monitoring", Date.Now))
 57            End If
 58
 59            ' If this application is idle, then start to monitor and disable the editors.
 60        Else
 61            Dim success As Boolean = StartMonitor()
 62            If success Then
 63                btnMonitor.Text = "Stop Monitor"
 64                cmbHives.Enabled = False
 65                tbRegkeyPath.ReadOnly = True
 66                isMonitoring = True
 67                lstChanges.Items.Add(String.Format("{0} Start monitoring", Date.Now))
 68            End If
 69        End If
 70
 71    End Sub
 72
 73    ''' <summary>
 74    ''' Check whether the key to be monitored exists, and then 
 75    ''' start ManagementEventWatcher to watch the RegistryKeyChangeEvent
 76    ''' </summary>
 77    ''' <returns>True if the ManagementEventWatcher starts successfully.</returns>
 78    Private Function StartMonitor() As Boolean
 79        Dim hive As RegistryKey = TryCast(cmbHives.SelectedValue, RegistryKey)
 80        Dim keyPath = tbRegkeyPath.Text.Trim()
 81
 82        Try
 83            watcher = New RegistryWatcher(hive, keyPath)
 84
 85            ' The constructor of RegistryWatcher may throw a SecurityException when
 86            ' the key to monitor does not exist. 
 87        Catch _ArgumentException As ArgumentException
 88            MessageBox.Show(_ArgumentException.Message)
 89            Return False
 90
 91            ' The constructor of RegistryWatcher may throw a SecurityException when
 92            ' current user does not have the permission to access the key to monitor. 
 93        Catch _SecurityException As System.Security.SecurityException
 94            Dim message As String = String.Format("You do not have permission to access the key {0}\{1}.", hive.Name, keyPath)
 95            MessageBox.Show(message)
 96            Return False
 97        End Try
 98
 99        Try
100
101            ' Set up the handler that will handle the change event.
102            AddHandler watcher.RegistryKeyChangeEvent, AddressOf watcher_RegistryKeyChangeEvent
103
104            ' Start listening for events.
105            watcher.Start()
106            Return True
107        Catch comException As System.Runtime.InteropServices.COMException
108            MessageBox.Show("An error occurred: " & comException.Message)
109            Return False
110        Catch managementException_Renamed As ManagementException
111            MessageBox.Show("An error occurred: " & managementException_Renamed.Message)
112            Return False
113        End Try
114
115    End Function
116
117    ''' <summary>
118    ''' Stop listening for events.
119    ''' </summary>
120    ''' <returns>True if ManagementEventWatcher stops successfully.</returns>
121    Private Function StopMonitor() As Boolean
122        Try
123            watcher.Stop()
124            Return True
125        Catch _ManagementException As ManagementException
126            MessageBox.Show("An error occurred: " & _ManagementException.Message)
127            Return False
128        Finally
129            watcher.Dispose()
130        End Try
131    End Function
132
133    ''' <summary>
134    ''' Handle the RegistryKeyChangeEvent.
135    ''' </summary>
136    Private Sub watcher_RegistryKeyChangeEvent(ByVal sender As Object, ByVal e As RegistryKeyChangeEventArgs)
137        Dim newEventMessage As String = String.Format( _
138            "{0} The key {1}\{2} changed", _
139            e.TIME_CREATED.ToLocalTime(), _
140            e.Hive, _
141            e.KeyPath)
142        lstChanges.Items.Add(newEventMessage)
143    End Sub
144
145End Class