Figure 1 Enumerating Processes using System;
using System.Management;
namespace WorkWithProcesses
{
class Class1
{
static void Main(string[] args)
{
ManagementClass processClass = new ManagementClass
(@"root\cimv2:Win32_Process");
foreach (ManagementObject processInstance in
processClass.GetInstances())
{
Console.WriteLine(processInstance["Caption"].ToString());
}
//set up an event watcher and a handler for the process
//creation event
ManagementEventWatcher watcher = new ManagementEventWatcher (
new WqlEventQuery ("SELECT * FROM __InstanceCreationEvent
WITHIN 1 " +
@"WHERE TargetInstance ISA ""Win32_Process"""));
EventHandler handler = new EventHandler();
watcher.EventArrived += new EventArrivedEventHandler
(handler.Arrived);
watcher.Start(); //start watching for events
System.Threading.Thread.Sleep(180000); //wait for 3 minutes
watcher.Stop();
Console.WriteLine("Done watching for events");
}
}
public class EventHandler
{
public void Arrived(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("Process created = " +
((ManagementBaseObject)e.NewEvent["TargetInstance"])["Caption"]);
}
}
}
Figure 3 Firing Management Events in C# using System;
using System.Management.Instrumentation;
using System.Configuration.Install;
using ConsoleApplication16.ROOT.CIMV2;
// Specify which namespace the management event class is created in
[assembly:Instrumented("Root/Default")]
// We will run InstallUtil.exe utility against this assembly
[System.ComponentModel.RunInstaller(true)]
public class MyInstaller : DefaultManagementProjectInstaller {}
namespace EventProviderApp
{
[InstrumentationClass(InstrumentationType.Event)]
public class BabyBorn
{
public BabyBorn(int weight)
{
Weight = weight;
Instrumentation.Fire(this);
}
public int Weight; //in ounces
static void Main(string[] args)
{
for (int weight = 120; weight < 125; weight++)
{
BabyBorn myBabyEvt = new BabyBorn(weight);
}
}
}
}
Figure 6 A Strongly Typed Wrapper Class Makes for Easier Programming .gif) |