我是WMI的新手,我需要在C#服务中实现RegistryValueChangeEvent。
我需要一个事件处理程序,每次更改一组注册表值时都会触发该事件处理程序。我希望行为类似于FileSystemWatcher类的Changed事件,但是对于注册表值。
如果我可以使用其他一些技术来完成相同的任务,我也会感激。我的最低要求是它比现在更好的解决方案:每20秒轮询一次,并将注册表值与最后的结果进行比较。
请在答案中提供示例代码。如果我只能看一个注册表值的示例,那就没问题了。
我需要.Net 2.0中的解决方案
感谢。
答案 0 :(得分:27)
// ---------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="">
//
// </copyright>
// <summary>
// Defines the WmiChangeEventTester type.
// </summary>
// ---------------------------------------------------------------------------------------------------------------------
namespace WmiExample
{
using System;
using System.Management;
/// <summary>
/// </summary>
public class WmiChangeEventTester
{
/// <summary>
/// Initializes a new instance of the <see cref="WmiChangeEventTester"/> class.
/// </summary>
public WmiChangeEventTester()
{
try
{
// Your query goes below; "KeyPath" is the key in the registry that you
// want to monitor for changes. Make sure you escape the \ character.
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM RegistryValueChangeEvent WHERE " +
"Hive = 'HKEY_LOCAL_MACHINE'" +
@"AND KeyPath = 'SOFTWARE\\Microsoft\\.NETFramework' AND ValueName='InstallRoot'");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
Console.WriteLine("Waiting for an event...");
// Set up the delegate that will handle the change event.
watcher.EventArrived += new EventArrivedEventHandler(HandleEvent);
// Start listening for events.
watcher.Start();
// Do something while waiting for events. In your application,
// this would just be continuing business as usual.
System.Threading.Thread.Sleep(100000000);
// Stop listening for events.
watcher.Stop();
}
catch (ManagementException managementException)
{
Console.WriteLine("An error occurred: " + managementException.Message);
}
}
/// <summary>
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
private void HandleEvent(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("Received an event.");
// RegistryKeyChangeEvent occurs here; do something.
}
/// <summary>
/// </summary>
public static void Main()
{
// Just calls the class above to check for events...
WmiChangeEventTester receiveEvent = new WmiChangeEventTester();
}
}
}
答案 1 :(得分:3)
您是否仅限于WMI? 如果不是,您可以使用RegNotifyChangeKeyValue
之类的RegistryMonitor包装器答案 2 :(得分:2)
正如其他人所指出的那样,你真的不需要WMI。我也没有使用过RegistryMonitor。
如果您需要一个示例,则页面本身已经有RegistryMonitor的示例代码。您是否在代码项目中向下滚动到这一位:
public class MonitorSample
{
static void Main()
{
RegistryMonitor monitor = new
RegistryMonitor(RegistryHive.CurrentUser, "Environment");
monitor.RegChanged += new EventHandler(OnRegChanged);
monitor.Start();
while(true);
monitor.Stop();
}
private void OnRegChanged(object sender, EventArgs e)
{
Console.WriteLine("registry key has changed");
}
}
答案 3 :(得分:0)