2009-06-09 59 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(); 
    } 
} 
相關問題