Search code examples
c#notificationsdispose

Disposing of Notifications C#


I have an app where when there is a change to a label it creates a clickable notification. It all works perfectly however the notification icon stays in the system tray and you end up with loads of them. I know I can use the notification.dispose but I don't know where to use it. Here is the code:

        private void label1_TextChanged(object sender, EventArgs e)
        {
            string strNumber = label1.Text;

            if (strNumber.StartsWith("0") || strNumber.StartsWith("+44") & strNumber.Length < 17 & strNumber.Length > 8)
            {
                var notification = new System.Windows.Forms.NotifyIcon()
                {
                    Visible = true,
                    Icon = System.Drawing.SystemIcons.Question,
                    BalloonTipTitle = "Click here to dial",
                    BalloonTipText = Clipboard.GetText(TextDataFormat.Text),
                };
                notification.ShowBalloonTip(5000);
                notification.BalloonTipClicked += new System.EventHandler(notification_BalloonTipClicked);

               // notification.Dispose();
            }
        }

I have commented out the notification.Dispose at the bottom because if I do that it disposes of it straight away and I can't click it. So I don't know where else I am supposed to add this code so that it removes the icon for it in the tray either when you click the notification or if you just wait and let it time out. I can't place it outside of this block of text as it's a local variable.

I'm a complete novice at coding so any help would be appreciated.


Solution

  • You need to subscribe to the events that the NotifyIcon presents.

    Create functions for handling timeout and click then

    notification.BallotTipClicked += MyClickFunction;
    notification.BallotTipClosed += MyCloseFunction;
    
    private void MyClickFunction(Object sender, EventArgs e) {
    
       System.Windows.Forms.NotifyIcon notification = sender as System.Windows.Forms.NotifyIcon;
       notification.Dispose()
    }