Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

c# - Receive notification when RegistryKey Value was changed

I want a notification when a specific RegistryKey in HKEY_CURRENT_USER is changed. So far I tried this via WMI with no success:

var query = new WqlEventQuery(string.Format(
"SELECT * FROM RegistryKeyChangeEvent WHERE Hive='{0}' AND KeyPath='{1}' AND ValueName='{2}'",
                hive, keyPath.Replace("",""), valueName));
_watcher = new ManagementEventWatcher(query);
_watcher.Scope.Path.NamespacePath = @"rootdefault";
_watcher.EventArrived += (sender, args) => KeyValueChanged();
_watcher.Start();

(Error was "Not found")

My second approach was using the WBEM Scripting COM component with the intent to port the example from http://msdn.microsoft.com/en-us/library/aa393042(VS.85).aspx to c# but I didn't find any usage samples for the WBEM COM in c#

I found this http://www.codeproject.com/KB/system/registrymonitor.aspx class, but it didn't fit my needs as this class only monitors the whole key and I only want a notification when a specific value (specified via the ValueName in the samples above) gets changed.

EDIT: If you change the Hive to HKEY_CURRENT_USER in the msdn vbscript example, it stops working. I couldn't find anything about this behaviour but a link from 2003

EDIT2: Changes to the HKEY_CLASSES_ROOT and HKEY_CURRENT_USER hives are not supported by RegistryEvent or classes derived from it, such as RegistryValueChangeEvent. (MSDN)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I finally solved the problem and got the WMI query version to work:

var currentUser = WindowsIdentity.GetCurrent();
var query = new WqlEventQuery(string.Format(
"SELECT * FROM RegistryValueChangeEvent WHERE Hive='HKEY_USERS' AND KeyPath='{0}\\{1}' AND ValueName='{2}'",
currentUser.User.Value, keyPath.Replace("",""), valueName));
_watcher = new ManagementEventWatcher(query);
_watcher.EventArrived += (sender, args) => KeyValueChanged();
_watcher.Start();

I found this "hack" at http://www.codeproject.com/Messages/2844468/Monitoring-HKEY_CURRENT_USER.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...