我正在尝试使用 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'";
我是一名优秀的程序员,十分优秀!