0

I overridden the FormClosing event to minimize to system tray when clicked. Here is my code:

    private void OnFormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.UserClosing)
        {
            e.Cancel = true;
            this.Hide();

            notifyIcon.BalloonTipText = "Server minimized.";
            notifyIcon.ShowBalloonTip(3000);
        }
        else
        {
            this.Close();
        }
    }

And I also set the notifyIcon's DoubleClick event as well, here is the code:

    private void showWindow(object sender, EventArgs e)
    {
        Show();
        WindowState = FormWindowState.Normal;
    }

I have two questions regarding this:

1) Now, when the upper-right "X" button is clicked, the application is minimized to the tray, but I can't close it (makes sense...). I wish to click right click on the icon in the system tray, and that it will open a menu with, let's say, these options: Restore, Maximize and Exit.

2) (This is may be related to me exiting the program with shift+f5 since I can't, for now, close my application because of the changes I mentioned). When the application quits, after I minimzed it to the tray, the icon is left in the tray, until I pass over it with my mouse. How can I fix it?

Idanis
  • 1,918
  • 6
  • 38
  • 69

1 Answers1

0

Just add a variable that indicates that the close was requested by the context menu. Say:

    private bool CloseRequested;

    private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
        CloseRequested = true;
        this.Close();
    }

    protected override void OnFormClosing(FormClosingEventArgs e) {
        base.OnFormClosing(e);
        if (e.CloseReason == CloseReason.UserClosing && !CloseRequested) {
            e.Cancel = true;
            this.Hide();
        }
    }

Be sure to not call Close() in the FormClosing event handler, that can cause trouble when the Application class iterates the OpenForms collection. The possible reason that you are left with the ghost icon. No need to help.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Hi. Thanks for the help, but what's the role of the `exitToolStripMenuItem_Click` method? – Idanis Jan 27 '13 at 13:19
  • It is the Click event handler for the Exit command on your context menu, the one you mentioned in your question and also has the Restore and Maximize commands. Odd question btw. – Hans Passant Jan 27 '13 at 13:29
  • ok, sorry for the ignorance, I wasn't familiar with the contextmenustrip...Now I understand everything you wrote. I applied it, and I can now use right click on the form, and I get the context menu. But, if I right click the icon in the taskbar - I get nothing...what am I missing? – Idanis Jan 27 '13 at 14:03
  • You forgot to set the NotifyIcon's ContextMenuStrip property. – Hans Passant Jan 27 '13 at 14:08