[英]C# application closing problem
我希望我的应用程序能够在单击close(X)按钮时将其最小化到系统托盘。
而且,只有在主应用程序窗口上单击其他按钮/菜单或单击系统托盘上下文菜单项才能关闭它。
我能够使窗口最小化以关闭托盘。
但是我面临的问题是,我现在无法关闭该应用程序。
这是我的代码(无法关闭该应用程序):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void hideToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Visible = false;
}
private void showToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Visible = true;
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.DoEvents();
Application.Exit();
}
private void Form1_Resize(object sender, EventArgs e)
{
if (FormWindowState.Minimized == this.WindowState)
{
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(500);
this.Hide();
}
else if (FormWindowState.Normal == this.WindowState)
{
notifyIcon1.Visible = false;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.WindowState = FormWindowState.Minimized;
}
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
}
在按钮中,设置一个字段,例如:
bool isClosing;
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
isClosing = true;
Close();
}
并在“结束”中进行检查:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(!isClosing) {
e.Cancel = true;
this.WindowState = FormWindowState.Minimized;
}
}
这是因为它总是会在您取消事件的地方触发表单关闭事件处理程序。
在此放置条件,如果表单已最小化,则跳过取消事件
在您要覆盖关闭行为的地方添加一个标志,并通过检查close事件参数上的CloseReason枚举值来覆盖其他退出情况。
bool m_NeedClose = false;
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
m_NeedClose = true;
Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(m_NeedClose ||
(e.CloseReason != CloseReason.UserClosing))
{
return;
}
e.Cancel = true;
this.WindowState = FormWindowState.Minimized;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.