ProfK
ProfK

Reputation: 51063

Multiple NotifyIcon images in task status area

I have a WPF application I like to keep quietly running when the user closes the main window. I do this using a NotifyIcon in the task status area, and use it as such in my App.xaml.cs:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    _notifyIcon = new NotifyIcon();
    _notifyIcon.DoubleClick += (sender, args) => ShowMainWindow();
    _notifyIcon.Icon = Wpf.Properties.Resources.QDrive;
    _notifyIcon.Visible = true;
    CreateContextMenu();

    new Bootstrapper().Run();

    Debug.Assert(Current.MainWindow != null, "Application.Current.MainWindow != null");
    Current.MainWindow.Closing += MainWindowOnClosing;
}

private void CreateContextMenu()
{
    _notifyIcon.ContextMenuStrip = new ContextMenuStrip();
    _notifyIcon.ContextMenuStrip.Items.Add("Open Q-Drive...").Click += (sender, args) => ShowMainWindow();
    _notifyIcon.ContextMenuStrip.Items.Add("Exit").Click += (sender, args) => ExitApplication();
}

private void ExitApplication()
{
    _isExit = true;
    Debug.Assert(Current.MainWindow != null, "Application.Current.MainWindow != null");
    Current.MainWindow.Close();
    _notifyIcon.Visible = false;
    _notifyIcon.Dispose();
    _notifyIcon = null;
}

Yet after closing and restarting the app a few times while debugging in VS2017, I have multiple icons visible, of which all but the active one vanish on mouse-over. I notice this is a bug with a few other applications I use that I have not developed myself.

How can I prevent this?

Upvotes: 0

Views: 68

Answers (1)

Ryan Lundy
Ryan Lundy

Reputation: 210080

NotifyIcon leaves its icon behind if you exit the program without hiding the icon first.

You're hiding it in ExitApplication, of course. I suspect that while debugging, though, you're not always exiting the program by selecting the Exit item on the menu, but simply by stopping Visual Studio. That's why the orphaned icon gets left behind.

This isn't unusual in development, but it won't affect your users unless they use the Task Manager to force an immediate halt to your program.

If it bothers you, though, you could write a global exception handler (something you should probably do anyway) and in that handler you could hide the icon, taking care first to make sure it still exists.

Of course, if you break on exceptions in Visual Studio and you abruptly terminate the program, even that global exception handler won't hide the NotifyIcon.

Upvotes: 1

Related Questions