Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 任务状态区域中有多个NotifyIcon图像_Wpf_Notifyicon - Fatal编程技术网

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

Wpf 任务状态区域中有多个NotifyIcon图像,wpf,notifyicon,Wpf,Notifyicon,我有一个WPF应用程序,我喜欢在用户关闭主窗口时保持安静运行。我使用任务状态区域中的Notify图标执行此操作,并在我的App.xaml.cs中使用它: protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); _notifyIcon = new NotifyIcon(); _notifyIcon.DoubleClick += (sender, args) => ShowMa

我有一个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,我还没有自己开发


如何防止出现这种情况?

NotifyIcon
如果退出程序而不先隐藏图标,则会将其图标留在后面

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

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

但是,如果它困扰您,您可以编写一个(您可能无论如何都应该做的事情),并在该处理程序中隐藏图标,首先要注意确保它仍然存在

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