I am using the following C# code in a Windows Service (which runs as NT_AUTHORITY\SYSTEM
) to create an event handler for receiving process creation events (using WMI and WQL):
string queryString = "SELECT * FROM Win32_ProcessStartTrace";
ManagementEventWatcher watcher = new ManagementEventWatcher(new WqlEventQuery(queryString));
watcher.EventArrived += new EventArrivedEventHandler(ProcessStartEvent);
watcher.Start();
In ProcessStartEvent
:
int processId = int.Parse(e.NewEvent.Properties["ProcessId"].Value.ToString());
Process proc = Process.GetProcessById(processId);
Out("Received process: " + proc.ProcessName);
The problem I'm having is that (for some strange reason) not every process start is captured and reported by the program. If I start about 6 processes simultaneously, one may not show up in the output.
I've tried to do some research on capturing process creation events using WMI, but there is limited information available. I've seen that it is also possible to capture process starts using something similar to:
SELECT TargetInstance
FROM __InstanceCreationEvent
WITHIN 2
WHERE TargetInstance ISA 'Win32_Process'
(As seen in this Stack Overflow answer)
Are there any major differences between using __InstanceCreationEvent
and Win32_ProcessStartTrace
? Could this be the cause of my problems?
Is there an explanation as to why I'm not receiving events for all process starts? Is there something more obvious that I'm doing wrong here?
Both methods are valid but works in differents ways.
When you uses the __InstanceCreationEvent
WMI class you are using a intrinsic event which means which you are monitoring changes in the standard WMI data model (this works like a trigger in a table).
When you uses the Win32_ProcessStartTrace
you are using a Extrinsic event that means you are using a specialized event class made for a specific task in this case monitor the process creation.
Now back to your issue, the best way to avoid the "lost" of some events is creating a permanent event consumer
.