2009-06-09 58 views
9

创建新流程时是否有任何事件发生?我正在编写一个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); 
     } 

回答

12

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(); 
    } 
} 
相关问题