2011-08-03 68 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