Search code examples
c#winformsapplication-close

C# application closing problem


I want my application such that, it will minimize to System Tray on clicking the close(X) button.

And it will only be closed by clicking a different button/menu on the main application window or clicking a system tray context menuItem.

I am able to make the window minimize to tray on close.

But the problem I am facing is, I am now unable to close the application.

This is my code (it is unable to close the application):

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;
        }        
    }

Solution

  • In the button, set a field, for example:

    bool isClosing;
    private void quitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        isClosing = true;
        Close();
    }
    

    and check this in the "closing":

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