【问题标题】:How to detect differentiate external wm_close vs internally triggered by form.close()如何检测区分外部 wm_close 与 form.close() 内部触发
【发布时间】:2011-08-03 17:35:40
【问题描述】:

这是一个 C# 应用程序,它作为通知图标位于托盘中并执行其操作,直到有人右键单击它并选择关闭(菜单选项),或者它从外部应用程序或操作系统获取 wm_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 发送应用程序。处理这种情况的正确方法是什么?谢谢你

【问题讨论】:

  • Udpdate:或者调用 Application.exit 以防 Wmclose 而不是 form.close() 也解决了这个问题。仅供参考。

标签: c# winapi c#-4.0 c#-3.0 pinvoke


【解决方案1】:

处理表单Closing 事件。并且每当您想退出时,只需调用Close();,并使任何其他操作依赖于关闭事件内部的关闭,而不是在WndProctoolStripMenuItemExit_Click 处理它,所以:

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
}

CloseReasonhere的更多成员。

【讨论】:

    【解决方案2】:

    从 toolStripMenuItemExit_Click 和 WndProc 中删除 CleanUp() 调用。

    在主窗口窗体中添加一个 FormClosing() 事件处理程序(假设你有一个)。同样,假设您有一个主窗体窗口,为什么还要有一个 WndProc?

    CleanUp() 只会执行一次,但您仍然会有两条日志消息,尽管两者都是准确的。

    【讨论】:

    • 谢谢,我正在处理 WndProc() 中的其他案例。因此需要它。 Jalal 上面的详细回答被问题解决了。
    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多