我正在尝试使用WMI事件来监视在本地计算机上启动的进程。我使用以下代码测试事件并监视进程:

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));
    }
}


但是,所有TargetInstance属性都存在,但在启动进程时其值为null。有任何想法吗?

最佳答案

由于没有检索WQL句子中的字段,因此您会得到空值-

取代这个

  string queryString = "SELECT TargetInstance FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA 'Win32_Process'";


这样

  string queryString = "SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA 'Win32_Process'";

09-07 01:30