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

11 c# notifyicon winforms

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

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

        if (notifyIcon != null)
        {
            notifyIcon.Visible = false;
            notifyIcon.Dispose();
        }
Run Code Online (Sandbox Code Playgroud)

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

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

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

干杯.

编辑

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

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

就在应用程序在此处检查升级后触发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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这有帮助吗?

Dav*_*ave 12

在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
            }
        }
Run Code Online (Sandbox Code Playgroud)


Mat*_*ley 4

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)