Issue with NotifyIcon not disappearing on Winforms App

bUrGe picture bUrGe · Jul 1, 2009 · Viewed 13.4k times · Source

I've got a .Net 3.5 C# Winforms app. It's got no GUI as such, just a NotifyIcon with a ContextMenu.

I've tried to set the NotifyIcon to visible=false and dispose of it in the Application_Exit event, as follows:

        if (notifyIcon != null)
        {
            notifyIcon.Visible = false;
            notifyIcon.Dispose();
        }

The app gets to the code inside the brackets, but throws a null ref exception when it tries to set Visible = false.

I've read in a few places to put it in the form closing event, but that code never gets hit (maybe as I don't have a form showing as such?).

Where can I put this code so it actually works? If I don't put it in, I get the annoying lingering icon in the tray until you move the mouse over it.

Cheers.

EDIT

Just something extra I've noticed...........

I'm using ClickOnce in the app.........if I just exit the app via the ContextMenu on the NotifyIcon, no exception is logged.

Just when the Application_Exit event is fired after the applicaiton has checked for an upgrade here..

private void CheckForUpdate()
{
    EventLogger.Instance.LogEvent("Checking for Update");
    if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.CheckForUpdate())
    {
        EventLogger.Instance.LogEvent("Update available - updating");
        ApplicationDeployment.CurrentDeployment.Update();
        Application.Restart();
    }
}

Does this help?

Answer

Dave picture Dave · Nov 21, 2010

On Windows 7, I had to also set the Icon property to null. Otherwise, the icon remained in the tray's "hidden icons" popup after the application had closed. HTH somebody.

// put this inside the window's class constructor
Application.ApplicationExit += new EventHandler(this.OnApplicationExit);


        private void OnApplicationExit(object sender, EventArgs e)
        {

            try
            {
                if (trayIcon != null)
                {
                    trayIcon.Visible = false;
                    trayIcon.Icon = null; // required to make icon disappear
                    trayIcon.Dispose();
                    trayIcon = null;
                }

            }
            catch (Exception ex)
            {
                // handle the error
            }
        }