NotifyIcon的问题在Winforms App上没有消失

我有一个.Net 3.5 C#Winforms应用程序。 它没有这样的GUI,只是一个带有ContextMenu的NotifyIcon。

我试图将NotifyIcon设置为visible = false并将其处理在Application_Exit事件中,如下所示:

if (notifyIcon != null) { notifyIcon.Visible = false; notifyIcon.Dispose(); } 

应用程序获取括号内的代码,但在尝试设置Visible = false时抛出空引用exception。

我已经阅读了几个地方把它放在表格结束事件中,但是那个代码永远不会被击中(可能因为我没有这样的表格?)。

我在哪里可以放置这些代码以便实际工作? 如果我没有把它放入,我会在托盘中看到烦人的挥之不去的图标,直到你将鼠标移到它上面。

干杯。

编辑

只是额外的东西我注意到了………..

我在应用程序中使用ClickOnce ………如果我只是通过NotifyIcon上的ContextMenu退出应用程序,则不会记录任何exception。

就在应用程序在此处检查升级后触发Application_Exit事件时…

 private void CheckForUpdate() { EventLogger.Instance.LogEvent("Checking for Update"); if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.CheckForUpdate()) { EventLogger.Instance.LogEvent("Update available - updating"); ApplicationDeployment.CurrentDeployment.Update(); Application.Restart(); } } 

这有帮助吗?

在Windows 7上,我还必须将Icon属性设置为null。 否则,应用程序关闭后,图标将保留在托盘的“隐藏图标”弹出窗口中。 HTH有人。

 // put this inside the window's class constructor Application.ApplicationExit += new EventHandler(this.OnApplicationExit); private void OnApplicationExit(object sender, EventArgs e) { try { if (trayIcon != null) { trayIcon.Visible = false; trayIcon.Icon = null; // required to make icon disappear trayIcon.Dispose(); trayIcon = null; } } catch (Exception ex) { // handle the error } } 

这段代码对我有用,但我不知道你是如何让你的应用程序保持活着的,所以……不用多说:

 using System; using System.Drawing; using System.Windows.Forms; static class Program { static System.Threading.Timer test = new System.Threading.Timer(Ticked, null, 5000, 0); [STAThread] static void Main(string[] args) { NotifyIcon ni = new NotifyIcon(); ni.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); ni.Visible = true; Application.Run(); ni.Visible = false; } static void Ticked(object o) { Application.Exit(); } } 

这就是我在WPF中所做的。

我将这个与David Anson的Minimize to tray示例应用程序结合使用,它允许您将托盘图标连接到窗口(您可能打开了多个窗口)。

刚刚将此代码添加到MinimizeToTrayInstance的构造函数中。

 _window.Closed += (s, e) => { if (_notifyIcon != null) { _notifyIcon.Visible = false; _notifyIcon.Dispose(); _notifyIcon = null; } }; 

有时Application_Exit事件可以多次引发只需把notifyIcon = null; 到底

 if (notifyIcon != null) { notifyIcon.Visible = false; notifyIcon.Dispose(); notifyIcon = null; } 

这段代码对我有用

 this.Closed += (a, b) => { if (notifyIcon1 != null) { notifyIcon1.Dispose(); notifyIcon1.Icon = null; notifyIcon1.Visible = false; } }; 

您是否已重写已初始化notifyIcon的对象的dispose方法以处置notifyIcon?

 protected override void Dispose(bool disposing) { if (disposing) { notifyIcon.Dispose(); notifyIcon = null; } base.Dispose(disposing); }