0

There should be a pretty straightforward answer to this question but I can´t seem to find a solution. I have seen similar questions on SO (like NotifyIcon remains in Tray even after application closing but disappears on Mouse Hover) but they don´t cover my case.

I have a WPF application with a Notification Icon that is set up inside the MainWindow method:

InitializeComponent();
myIcon = new System.Windows.Forms.NotifyIcon();
myIcon.Icon = someFancyIcon;
myIcon.Visible = true;

On the xaml I have defined the Window attribute Closing="Window_Closing" so that when the window is closed it calls:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    Log.Info("Closing application");            
    myIcon.Icon = null;
    Environment.Exit(0);            
}

If I ran the application and close it in the normal way, Window_Closing is called and the notification icon disappears as expected (and info is output to the log).

Problem is: this application is monitored by another process (out of my control), and that other process sometimes kills the WPF application process so that Window_Closing is never called and my application notification icon keeps on lingering on the notification area until you hover your mouse over it. Since the monitoring process can restart my application and close it again several times, the notification area is soon filled with copies of the notification icon.

How can I remove the notification icon so that even if my application is finished in some abnormal way the icon disappears?

Ada
  • 261
  • 1
  • 3
  • 14

1 Answers1

0

In common case, you can't do that due how Windows Tray is designed. All the tray icons are driven by their apps: they're created by and removed by the corresponding app who owns that icon(s).

If the app is terminated abnormally the tray has no clue about that. The only case is to move mouse pointer over the orphaned icon and then it will be removed from tray as no corresponding app found alive.

What can we do then? Do not kill the app. Instead, send it a message causing it to close (so, all handlers would be called then and all resources are to be freed, including tray icons as well).

Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42