我正在开发一个C#应用程序,当用户点击X时,应用程序在trayicon内被最小化.像这样:
private void frmChat_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
Hide();
}
Run Code Online (Sandbox Code Playgroud)
该应用程序非常简单(只有一种形式).问题是我无法正确关闭应用程序.当用户权限点击托盘图标并且他选择"退出"时,他应该能够关闭该应用程序.问题是即使托盘图标被卸载并且窗体关闭,应用程序仍然在任务管理器中显示为活动应用程序.我正在关闭这样的应用程序:
private void chiudiToolStripMenuItem_Click(object sender, EventArgs e)
{
trayIcon.Dispose();
this.Close();
Application.Exit();
}
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么?
我曾经做过类似的事情.
您需要知道导致表单关闭的原因.因此,当您单击X时,会有一个特定的原因传递给FormClosing事件.像这样:
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
// don't close just yet if we click on x
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
this.Hide();
}
}
Run Code Online (Sandbox Code Playgroud)
另外,我还有上下文菜单中的其他代码退出点击:
private void tsmiExit_Click(object sender, EventArgs e)
{
// close the application forefully
TerminateApplication();
}
/// <summary>
/// Closes the Application.
/// </summary>
private void TerminateApplication()
{
// need to forcefully dispose of notification icon
this.notifyIcon1.Dispose();
// and exit the application
Application.Exit();
}
Run Code Online (Sandbox Code Playgroud)
编辑:
注意:单击X按钮时,关闭原因将是CloseReason.UserClosing.调用Application.Exit时,将使用CloseReason.ApplicationExitCall再次调用FormClosing.
结束编辑:
希望这可以帮助
Andez