创建新流程时是否有任何事件。我正在编写一个检查某些进程的c#应用程序,但我不想写一个无限循环来连续迭代所有已知进程。相反,我宁愿检查每个创建的进程,也可以遍历事件触发的所有当前进程。有什么建议吗?
Process[] pArray;
while (true)
{
pArray = Process.GetProcesses();
foreach (Process p in pArray)
{
foreach (String pName in listOfProcesses) //just a list of process names to search for
{
if (pName.Equals(p.ProcessName, StringComparison.CurrentCultureIgnoreCase))
{
//do some stuff
}
}
}
Thread.Sleep(refreshRate * 1000);
}
答案 0 :(得分:15)
WMI为您提供了一种监听流程创建的方法(以及大约一百万个其他内容)。请参阅my answer here。
void WaitForProcess()
{
ManagementEventWatcher startWatch = new ManagementEventWatcher(
new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
startWatch.EventArrived
+= new EventArrivedEventHandler(startWatch_EventArrived);
startWatch.Start();
}
static void startWatch_EventArrived(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("Process started: {0}"
, e.NewEvent.Properties["ProcessName"].Value);
if (this is the process I'm interested in)
{
startWatch.Stop();
}
}