Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate icons in system tray when the single instance app is reopened again without fully closed

Tags:

c#

Recently I found an issue in my single instance c# wpf desktop application. Initially, I opened my application and the icon was shown in the system tray. If I close the app using the close icon on windows, it will be run in the background and it can be opened from where it is left off using the system tray icon.

If I tried to open the app again like a regular way instead of using the system tray, there exists a duplicate icon in the system tray. However, hovering on the duplicate icons makes them disappear.

Is there any way to halt this issue of creating duplicates?

like image 566
Akash M Avatar asked Oct 21 '25 17:10

Akash M


1 Answers

As Raymond Chen stated, you are not properly deleting your notification icon in your code. When your app closes, you need to hide and dispose the NotifyIcon properly that you are using.

If you don't properly hide and dispose the icon, then the icon will remain in the system tray even though the process has terminated. If you hover the mouse over the icon, it will then disappear. To prevent this "phantom" tray icon, you need to clean it up.

For example:

MainWindow.xaml.cs:

using System.Windows.Forms;

public partial class MainWindow : Window
{
    private NotifyIcon taskbarIcon;

    public MainWindow()
    {
        InitializeComponent();
        this.Closing += MainWindow_Closing;
    }

    private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        if (taskbarIcon != null)
        {
            taskbarIcon.Visible = false;
            taskbarIcon.Dispose();
            taskbarIcon = null;
        }
    }
}
like image 79
Tam Bui Avatar answered Oct 23 '25 06:10

Tam Bui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!