2013-01-19 27 views
3

我有以下幾點:正確的事件處理程序來告訴我,當記事本關閉

class Program { 

    static void Main(string[] args) { 

     Process pr; 
     pr = new Process(); 
     pr.StartInfo = new ProcessStartInfo(@"notepad.exe"); 
     pr.Disposed += new EventHandler(YouClosedNotePad); 
     pr.Start(); 

     Console.WriteLine("press [enter] to exit"); 
     Console.ReadLine(); 
    } 
    static void YouClosedNotePad(object sender, EventArgs e) { 
     Console.WriteLine("thanks for closing notepad"); 
    } 

} 

當我關閉記事本我沒有得到我希望得到的消息 - 我怎麼修改,以便在返回的收盤記事本到控制檯?

回答

7

你需要兩樣東西 - enable raising events,並訂閱Exited事件:

static void Main(string[] args) 
    {    
     Process pr; 
     pr = new Process(); 
     pr.StartInfo = new ProcessStartInfo(@"notepad.exe"); 
     pr.EnableRaisingEvents = true; // first thing 
     pr.Exited += pr_Exited; // second thing 
     pr.Start(); 

     Console.WriteLine("press [enter] to exit"); 
     Console.ReadLine(); 

     Console.ReadKey(); 
    } 

    static void pr_Exited(object sender, EventArgs e) 
    { 
     Console.WriteLine("exited"); 
    } 
+2

@whytheq你確定嗎?它適用於我。順便說一句,正確答案+1。 –

+0

ahhh--沒有看到其他的魔法代碼行! – whytheq

+0

消息絕對應該在那裏。你是否啓用了事件? –

0

您要使用的Exited事件,而不是棄置:

pr.Exited += new EventHandler(YouClosedNotePad); 

你還需要確保EnableRaisingEvents屬性設置爲true:

pr.EnableRaisingEvents = true; 
+0

I t之前說過 - 控制檯中仍然沒有消息 – whytheq

+0

@whytheq:更新了答案,以包含在進程中缺少的標誌。 –

+0

謝謝 - 那正是我所錯過的。 – whytheq

相關問題