Akash M
Akash M

Reputation: 61

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

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?

Upvotes: 4

Views: 1402

Answers (1)

Tam Bui
Tam Bui

Reputation: 3048

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;
        }
    }
}

Upvotes: 4

Related Questions