I'm trying to use WMI events to monitor process which are started on the local computer. I use the following code to test the event and monitor for processes:
class Program
{
static void Main(string[] args)
{
ManagementEventWatcher watcher = WatchForProcessStart();
while(true) watcher.WaitForNextEvent();
}
private static ManagementEventWatcher WatchForProcessStart()
{
string scope = @"\\.\root\CIMV2";
string queryString = "SELECT TargetInstance FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA 'Win32_Process'";
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString);
watcher.EventArrived += ProcessStarted;
watcher.Start();
return watcher;
}
private static void ProcessStarted(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
targetInstance.Properties.Cast<PropertyData>().ToList().ForEach(p => Console.WriteLine("{0}={1}", p.Name, p.Value));
}
}
However the TargetInstance
propeties are all present but have a value of null when I start a process. Any ideas?
You are getting null values because you are not retrieving the fields in the WQL sentence-
replace this
string queryString = "SELECT TargetInstance FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA 'Win32_Process'";
by this
string queryString = "SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA 'Win32_Process'";