如何使用C#在Windows上检测外部应用程序启动的时刻?
我尝试了FilesystemWatcher,但它不起作用,因为文件并没有真正改变。而且,不断检查所有打开的进程可能有点过度杀伤。还有其他方法可以做到这一点吗?如果不能用C#实现,那么是否可以用C++实现(如果可以,请给我一个例子)。
我想这样做是为了记录日志。
你可以使用System.Management和WMI(Windows管理 Instrumentation)
class WMIEvent {
public static void Main() {
WMIEvent we = new WMIEvent();
ManagementEventWatcher w= null;
WqlEventQuery q;
try {
q = new WqlEventQuery();
q.EventClassName = "Win32_ProcessStartTrace";
w = new ManagementEventWatcher(q);
w.EventArrived += new EventArrivedEventHandler(we.ProcessStartEventArrived);
w.Start();
Console.ReadLine(); // block main thread for test purposes
}
finally {
w.Stop();
}
}
public void ProcessStartEventArrived(object sender, EventArrivedEventArgs e) {
foreach(PropertyData pd in e.NewEvent.Properties) {
Console.WriteLine("\n============================= =========");
Console.WriteLine("{0},{1},{2}",pd.Name, pd.Type, pd.Value);
}
}
using System.Management;
… 叹气 :p - Svish