2011-08-03 69 views
2

這是一個C#應用程序,作爲notifyicon坐在托盤中,並執行其任務,直到有人右鍵單擊它並選擇關閉(菜單選項)或它獲取來自外部應用程序或操作系統的wm_close在重啓過程中表示。如何檢測區分外部wm_close與內部由form.close觸發()

protected override void WndProc(ref Message m) 
{ 
    case Win32.WmClose: 
    //recvd message to shutdown 
    Program.Log.InfoFormat("Shutdown received at {0}", DateTime.Now); 
    CleanUp(); 
    this.Close(); //this is the main form 
    break; 

    //other case statements here 
} 

//somewhere else on menu exit of notify icon 
private void toolStripMenuItemExit_Click(object sender, EventArgs e) 
{ 
     Program.Log.InfoFormat("Manual EXIT at {0}", DateTime.Now); 
     CleanUp(); 
     this.Close(); //this is the main form 
} 

this.close()觸發另一個WM_CLOSE在tailspin中發送應用程序。處理這種情況的正確方法是什麼?謝謝

+0

Udpdate:或者在Wmclose而不是form.close()的情況下調用Application.exit也可以解決此問題。僅供參考。 – Gullu

回答

1

處理形式Closing事件。每當要退出只是調用Close();,並進行任何其他操作依賴於關閉事件中關閉,而不是把它處理爲WndProctoolStripMenuItemExit_Click,所以:的CloseReasonhere

private void OnFormCloseing(object sender, FormClosingEventArgs e) 
{ 
    string reason = string.Empty; 
    switch (e.CloseReason) 
    { 
     case CloseReason.UserClosing: 
      reason = "Manual EXIT"; 
      break; 

     case CloseReason.WindowsShutDown: 
      reason = "Shutdown received"; 
      break; 
    } 
    Program.Log.InfoFormat(reason + " at {0}", DateTime.Now); 
    CleanUp(); 
} 

private void toolStripMenuItemExit_Click(object sender, EventArgs e) 
{ 
    this.Close(); //this is the main form 
} 

多個成員。

+0

thx賈拉爾。問題解決了。 – Gullu

0

從toolStripMenuItemExit_Click和WndProc中刪除CleanUp()調用。

在主窗口窗體中添加FormClosing()事件處理程序(假設您有一個)。同樣,假設你有一個主窗體,爲什麼你有一個WndProc?

CleanUp()只會執行一次,但您仍然會有兩條日誌消息,但兩者都是準確的。

+0

thx,我正在處理WndProc()中的其他情況。因此需要它。 Jalal上面的詳細解答由問題解決。 – Gullu