Search code examples
c#disposeidisposablenotifyicon

Unable to Dispose Control (NotifyIcon)



In my homework application; I am required to create an application where I am also required to use a NotifyIcon.
I'm facing a problem where I cannot understand why the Code never reaches the Dispose Event.
I'm implementing "IDisposable"; (in order to be able to call Dispose on the NotifyIcon). However, after adding a breakpoint in the dispose event; I can see that I cannot reach it. I can't really understand the reason why it doesn't get there.

I'm currently following this thread to help me out with this control:
NotifyIcon remains in Tray even after application closing but disappears on Mouse Hover

Can anyone help me understanding the reason why this happens or what am I missing?

My Class Code:

    private NotifyIcon trayIcon;

    public void CreateTrayIcon()
    {
        if (trayIcon == null) { trayIcon = new NotifyIcon(); }
        trayIcon.Text = "My Tray Application";
        trayIcon.Icon = Properties.Resources.AppIcon;
        trayIcon.Disposed += TrayIcon_Disposed;

        trayIcon.Visible = true;
    }

    private void TrayIcon_Disposed(object sender, EventArgs e) // Unreacheable Code
    {
        if (trayIcon != null) 
        {
            trayIcon.Visible = false;
            trayIcon = null;
        }
    }

    protected virtual void Dispose(bool Disposing)
    {
        if (Disposing)
        {
           trayIcon.Dispose();
        }
    }
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

And Call NotifyIcon Dispose on Main Form; Form_ClosingEvent

private void Form_closing(object sender, FormClosingEventArgs e)
{
    trayIcon.Dispose();
}

Solution

  • I've found the problem.

    The reason behind my problem; was literally distraction. I was assuming the FormClosing Event was subscribed, (honestly: I was sure I had it subscribed. I must have made some kind of roll back and removed it by mistake).

    Solution: Just needed to check that the event was subscribed.