Below is a basic wraper class that I have found on the web. I works great
for my purposes. Sorry, it's in c# but you should be able to convert it to
VB with ease.
Implement:
Listener regKeyListner;
regKeyListner = new Listener(Registry.LocalMachine,
@"system\currentcontrolset\services\modem\enum");
regKeyListner.RegChange += new
RegistryWatcher.Listener.RegistryChange(regKeyListner_RegChange);
regKeyListner.RegErr += new
RegistryWatcher.Listener.RegistryError(regKeyListner_RegErr);
regKeyListner.start();
Class:
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Threading;
using System.Reflection;
namespace RegistryWatcher
{
/// <summary>
/// Summary description for Listener.
/// </summary>
public class Listener
{
const int ERROR_KEY_DELETED = 1018;
[Flags] public enum NotifyFilterFlags
{
REG_NOTIFY_CHANGE_NAME = 1,
REG_NOTIFY_CHANGE_ATTRIBUTES = 2,
REG_NOTIFY_CHANGE_LAST_SET = 4,
REG_NOTIFY_CHANGE_SECURITY = 8
};
[DllImport("advapi32.dll", EntryPoint="RegNotifyChangeKeyValue")]
static extern long RegNotifyChangeKeyValue(IntPtr key, bool watchSubTree,
int notifyFilter, IntPtr regEvent, bool async);
private IntPtr keyHandle;
private RegistryKey KeyToMonitor;
public delegate void RegistryChange(string regValue);
public delegate void RegistryError(Exception ex);
public event RegistryChange RegChange;
public event RegistryError RegErr;
public Listener(RegistryKey key, string subKey)
{
KeyToMonitor = key.OpenSubKey(subKey, false);
}
public void start()
{
Type regKeyType = KeyToMonitor.GetType();
FieldInfo field = regKeyType.GetField("hkey", BindingFlags.Instance |
BindingFlags.NonPublic);
keyHandle = (IntPtr)field.GetValue(KeyToMonitor);
WaitHandle NotifyEvent = new AutoResetEvent(false);
long RetVal = RegNotifyChangeKeyValue(keyHandle, true,
(int)NotifyFilterFlags.REG_NOTIFY_CHANGE_LAST_SET, NotifyEvent.Handle,
true);
System.Threading.ThreadPool.RegisterWaitForSingleObject(NotifyEvent, new
WaitOrTimerCallback(ValueChange), KeyToMonitor, -1, false);
}
public void stop()
{
if (!(KeyToMonitor == null))
KeyToMonitor.Close();
}
public void ValueChange(object state, bool timedOut)
{
try
{
int count = (int)KeyToMonitor.GetValue("Count");
if (count > 0)
RegChange(state.ToString());
else
start();
}
catch (Exception ex)
{
RegErr(ex);
}
}
}
}