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?