我是 WMI 的新手,我需要实现 RegistryValueChangeEvent在 C# 服务中。
我需要一个事件处理程序,每次更改一组注册表值中的任何一个时都会触发该事件处理程序。我想要类似于 FileSystemWatcher 的行为类(class)的Changed事件,但用于注册表值。
如果我可以使用其他一些技术来完成相同的任务,我也会很感激。我的最低要求是它是一个比我现在拥有的更好的解决方案:每 20 秒轮询一次并将注册表值与上次结果进行比较。
请在您的回答中提供示例代码。如果我能得到一个只监视一个注册表值的示例,那就没问题了。
我需要 .Net 2.0 中的解决方案
谢谢。
最佳答案
使用 WMI 有时会很有趣...我想我理解你的问题,所以请查看下面的代码片段,让我知道它是否是你正在寻找的。p>
// ---------------------------------------------------------------------------------------------------------------------
// <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();
}
}
}
关于c# - 注册表观察器 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/826971/