C#应用程序关闭问题

use*_*312 1 c# application-close winforms

我想要我的应用程序,它会在单击关闭(X)按钮时最小化到系统托盘.

只有通过单击主应用程序窗口上的其他按钮/菜单或单击系统托盘上下文menuItem才能关闭它.

我可以在关闭时使窗口最小化到托盘.

但我面临的问题是,我现在无法关闭应用程序.

这是我的代码(它无法关闭应用程序):

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;
        }        
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 8

在按钮中,设置一个字段,例如:

bool isClosing;
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
    isClosing = true;
    Close();
}
Run Code Online (Sandbox Code Playgroud)

并在"结束"中检查:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if(!isClosing) {
        e.Cancel = true;
        this.WindowState = FormWindowState.Minimized;
    }
}
Run Code Online (Sandbox Code Playgroud)