Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top