处理通知 C#

Disposing of Notifications C#

我有一个应用程序,当标签发生变化时,它会创建一个可点击的通知。这一切都完美无缺,但是通知图标保留在系统托盘中,您最终会收到大量通知图标。我知道我可以使用 notification.dispose 但我不知道在哪里使用它。这是代码:

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

我已经注释掉了底部的 notification.Dispose,因为如果我这样做,它会立即处理掉它,我无法点击它。所以我不知道我应该在哪里添加这段代码,以便它在您单击通知时或者如果您只是等待并让它超时时删除托盘中的图标。我不能将它放在这个文本块之外,因为它是一个局部变量。

我在编码方面完全是新手,所以任何帮助将不胜感激。

您需要订阅 NotifyIcon 显示的事件。

创建处理超时的函数然后点击

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()
}