__InstanceCreationEvent TargetInstance属性全为null

时间:2014-02-07 09:30:20

标签: c# wmi

我正在尝试使用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。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您正在获取空值,因为您没有检索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'";