Within the event handling procedure you can determine to which WMI class the instance that trigered event belongs and act accordingly. (e.NewEvent is of type ManagementBaseObject. In this sample e.NewEvent will always be an instance of __InstanceOperationEvent WMI class and its TargetInstance property will hold the reference to the Win32_Process or Win32Service instance that actually trigered the event).
You can also use the same event handler for multiple ManagementEventWatchers:
However, be careful when trying to use complex WQL queries as thay can degrade your system performance, so before using them 'in a production environment' be sure to test.
You can also use the same event handler for multiple ManagementEventWatchers:
using System;
using System.Management;
namespace WMISample
{
public class WMITest
{
public static void Main()
{
WqlEventQuery query1 = new WqlEventQuery(
@"Select * From __InstanceOperationEvent Within 1 " +
@"Where TargetInstance Isa 'Win32_Process' " +
@"And TargetInstance.Name = 'notepad.exe'");
WqlEventQuery query2 = new WqlEventQuery(
@"Select * From __InstanceOperationEvent Within 1 " +
@"Where TargetInstance Isa 'Win32_Service' " +
@"And TargetInstance.Name = 'MSSQL$SQLEXPRESS'");
ManagementEventWatcher watcher1 =
new ManagementEventWatcher(query1);
ManagementEventWatcher watcher2 =
new ManagementEventWatcher(query2);
Console.WriteLine("Waiting for an event");
watcher1.EventArrived +=
new EventArrivedEventHandler(HandleEvent);
watcher2.EventArrived +=
new EventArrivedEventHandler(HandleEvent);
try
{
watcher1.Start();
watcher2.Start();
System.Threading.Thread.Sleep(10000);
watcher1.Stop();
watcher2.Stop();
}
catch (ManagementException err)
{
Console.WriteLine("An error occurred: " + err.Message);
}
}
static void HandleEvent(object sender,
EventArrivedEventArgs e)
{
Console.WriteLine("Event : " +
((ManagementBaseObject)(e.NewEvent["TargetInstance"]))
.SystemProperties["__Class"].Value.ToString() + " " +
((ManagementBaseObject)(e.NewEvent["TargetInstance"]))["Name"]);
}
}
}
However, be careful when trying to use complex WQL queries as thay can degrade your system performance, so before using them 'in a production environment' be sure to test.
No comments:
Post a Comment