如何检测外部的wm_close与由form.close()内部触发的差异 [英] How to detect differentiate external wm_close vs internally triggered by form.close()
问题描述
这是一个C#应用程序,作为一个notifyicon放置在托盘中,并执行其操作,直到有人右键单击它并选择关闭(菜单选项),或者它从外部应用程序或通过操作系统在重新启动过程中获取wm_close为止.
This is a C# app that sits in the tray as a notifyicon and does its stuff until someone right clicks it and selects close (menu option) or it gets a wm_close from an external app or by the operating system say during a reboot.
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,以拖尾的方式发送应用程序.解决这种情况的正确方法是什么?谢谢
The this.close() triggers another WM_CLOSE sending the app in a tailspin. What is the correct way to handle this situation ? thank you
推荐答案
处理表单Closing
事件.并且只要您想退出,只需调用Close();
,并使其他任何操作都依赖于close事件内部的close而不是在WndProc
和toolStripMenuItemExit_Click
处进行处理,所以:
Handle form Closing
event. and whenever you want to exit just call Close();
, and make any other operation rely on closing inside the closing event instead of handling it at WndProc
and toolStripMenuItemExit_Click
, so:
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
}
CloseReason
的更多成员此处.
这篇关于如何检测外部的wm_close与由form.close()内部触发的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!