2014-01-19 64 views
2

運行我使用一個System.Timers.Timer檢查,如果某個進程在1000毫秒的間隔運行,如果是的話,它輸出一個字符串,例如:做的東西,如果某些進程不定時

System.Timers.Timer bTimer = new System.Timers.Timer(); 
bTimer.Elapsed += new ElapsedEventHandler(ChangeText); 
bTimer.Interval = 1000; 
bTimer.Enabled = true; 

private void ChangeText(object source, ElapsedEventArgs e) 
{ 
    foreach (Process clsProcess in Process.GetProcesses()) 
    { 
     if (clsProcess.ProcessName.Contains("notepad")) 
     { 
      lblText.Text = "Notepad is running."; 
     } 
     else 
     { 
      lblText.Text = "Notepad is not running."; 
     } 
    } 
} 

現在我想知道,是否有更有效的方法來做到這一點,沒有計時器?例如,監視正在運行的進程而不必每秒都讀內存的東西?

+1

檢查http://stackoverflow.com/questions/848618/net-events-for-process-executable-start – PashaPash

回答

1
var process = Process.GetProcessesByName("notepad").FirstOrDefault(); 
if (process == null) 
{ 
    MessageBox.Show("process is not running"); 
} 
else 
{ 
    process.EnableRaisingEvents = true; 
    process.Exited += (sender, args) => 
     { 
      MessageBox.Show("process exited"); 
     }; 
} 
相關問題