我有一个WPF应用程序,当用户关闭主窗口时,我喜欢保持静默运行。我使用任务状态区域中的NotifyIcon完成此操作,并在我的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,我使用的其他一些应用程序不是我自己开发的。
我如何防止这种情况发生?
发布于 2018-06-12 18:59:08
如果您先退出程序而不隐藏图标,则NotifyIcon会将其图标保留下来。
当然,您将其隐藏在ExitApplication中。但是,我怀疑在调试时,您并不总是通过选择菜单上的Exit项来退出程序,而是简单地停止Visual Studio。这就是为什么孤立的图标会被抛在后面。
这在开发中并不少见,但它不会影响您的用户,除非他们使用任务管理器强制立即停止您的程序。
但是,如果它困扰您,您可以编写一个global exception handler (无论如何您可能都应该这样做),并且可以在该处理程序中隐藏图标,首先要小心确保它仍然存在。
当然,如果在Visual Studio中遇到异常而突然终止程序,即使是全局异常处理程序也不会隐藏NotifyIcon。
https://stackoverflow.com/questions/50815451
复制相似问题