ArnoldS ArnoldS - 10 days ago 6
C# Question

Get which Registry value changed when RegNotifyChangeKeyValue triggered in c#

I am working on developing a wrapper class to monitor changes to a particular reg value.

I am using RegNotifyChangeKeyValue so whenever any value inside regKey "Software\Bla" updated, it fires an event.

But i have multiple values inside "Software\Bla", so how can i monitor changes to single value and not all ?

Answer

This is what you need to do, Step 1: Open registry location:

RegOpenKeyEx(registryHive, registrySubName, 0, STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_NOTIFY, out registryKey);

Step 2: Query reg value

RegQueryValueEx(registryKey, registryValueName, 0, ref type, pResult, ref size);

Step 3: Cache current value .. cachedValue = Marshal.PtrToStringAnsi(pResult);

step 4: Fire registry change event after comparing old value with new value..

         try
         {
            AutoResetEvent _eventNotify = new AutoResetEvent(false);

            WaitHandle[] waitHandles = new WaitHandle[] 
            {_eventNotify,    eventTerminate };

            while (!eventTerminate.WaitOne(0, true))
            {
                result = RegNotifyChangeKeyValue(registryKey, false, regFilter, _eventNotify.SafeWaitHandle, true);

                if (WaitHandle.WaitAny(waitHandles) == 0)
                {
                    retVal = RegQueryValueEx(registryKey, registryValueName, 0, ref type, pResult, ref size);
                    if (retVal == 0)
                    {
                        string currentValue = Marshal.PtrToStringAnsi(pResult);
                        if(!cachedValue.Equals(currentValue,StringComparison.InvariantCultureIgnoreCase))
                        {
                            OnRegistryChanged();
                        }
                    }
                }
            }
        }
        finally
        {
            if (registryKey != IntPtr.Zero)
            {
                RegCloseKey(registryKey);
            }
        }