我正在尝试创建一个等待程序运行的服务。
假设我运行 iTunes.exe,我的服务将执行类似显示“iTunes.exe 已启动”的消息框之类的操作。
实现此目的的唯一方法是定期获取进程列表并检查您等待的进程是否已启动:
while(Process.GetProcesses().All(p=>p.ProcessName.ToLower() != "itunes.exe"){
Thread.Sleep(2000);
}
//Do Something!
编辑:
更好的解决方案是查询 Windows Management Instrumentation 服务并监视新进程:
// Run this in another thread and make sure you dispose the event watcher before exit
var start = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
start.EventArrived += new EventArrivedEventHandler(delegate (object sender, EventArrivedEventArgs e) {
Console.WriteLine("Name: {0}, Command Line: {1}", e.NewEvent.Properties["ProcessName"].Value, e.NewEvent.Properties["Commandline"].Value);
});
start.Start();