代码之家  ›  专栏  ›  技术社区  ›  ProfK

任务状态区域中有多个NotifyIcon图像

  •  0
  • ProfK  · 技术社区  · 8 年前

    我有一个WPF应用程序,我喜欢在用户关闭主窗口时保持安静运行。我使用任务状态区域中的Notify图标来执行此操作,并在我的 App.xaml.cs :

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        _notifyIcon = new NotifyIcon();
        _notifyIcon.DoubleClick += (sender, args) => ShowMainWindow();
        _notifyIcon.Icon = Wpf.Properties.Resources.QDrive;
        _notifyIcon.Visible = true;
        CreateContextMenu();
    
        new Bootstrapper().Run();
    
        Debug.Assert(Current.MainWindow != null, "Application.Current.MainWindow != null");
        Current.MainWindow.Closing += MainWindowOnClosing;
    }
    
    private void CreateContextMenu()
    {
        _notifyIcon.ContextMenuStrip = new ContextMenuStrip();
        _notifyIcon.ContextMenuStrip.Items.Add("Open Q-Drive...").Click += (sender, args) => ShowMainWindow();
        _notifyIcon.ContextMenuStrip.Items.Add("Exit").Click += (sender, args) => ExitApplication();
    }
    
    private void ExitApplication()
    {
        _isExit = true;
        Debug.Assert(Current.MainWindow != null, "Application.Current.MainWindow != null");
        Current.MainWindow.Close();
        _notifyIcon.Visible = false;
        _notifyIcon.Dispose();
        _notifyIcon = null;
    }
    

    然而,在VS2017中调试时关闭并重新启动应用程序几次后,我看到了多个图标,其中除活动图标外,所有图标都会在鼠标上方消失。我注意到这是我使用的一些其他应用程序中的一个bug,我还没有自己开发。

    我怎样才能防止这种情况?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Ryan Lundy    7 年前

    NotifyIcon

    你把它藏起来了 ExitApplication 当然不过,我怀疑在调试时,您并不总是通过选择菜单上的退出项退出程序,而只是通过停止VisualStudio退出程序。这就是为什么孤儿图标会被抛在后面。

    这在开发中并不罕见,但它不会影响用户,除非他们使用任务管理器强制立即停止您的程序。

    不过,如果你感到困扰,你可以写一封信 global exception handler

    当然,如果在VisualStudio中中断异常并突然终止程序,即使全局异常处理程序也不会隐藏NotifyIcon。