我想使用 WPF 最小化应用程序到系统托盘。 “NotifyIcon”是实现此结果的唯一方法吗?如果是,在 WPF 中使用“NotifyIcon”需要哪个命名空间?
如果可以使用“NotifyIcon”,请提供一些提示,我如何在我的主窗口中使用它?
我的主窗口是,
public partial class MonthView : MetroWindow
{
public DateTime SelectedDate { get; set; }
public MonthView()
{
InitializeComponent();
calMain.DisplayDate = DateTime.Today;
Globals._globalController = new AppController();
Globals._globalController.appTaskManager.setupLocal();
Globals._globalController.setMonthViewWindow(this);
}
public void calItemSelectedDate(object sender, SelectionChangedEventArgs e)
{
DateTime d;
if (sender is DateTime)
{
d = (DateTime)sender;
}
else
{
DateTime.TryParse(sender.ToString(), out d);
}
SelectedDate = d;
ShowActivity(d);
}
public void ShowActivity(DateTime date)
{
DayView Activity = new DayView(date);
Activity.Show();
this.Hide();
}
private void SetButton_Click(object sender, RoutedEventArgs e)
{
SettingsView set = new SettingsView();
set.Show();
this.Hide();
}
}
NotifyIcon 在 WPF 中不像在 Forms 中那样实现,但您仍然可以使用 Windows 窗体 NotifyIcon,它驻留在 System.Windows.Forms namspace 中。
看看这些教程,它们可能会满足您的需求:
简单的解决方案,直接使用NotifyIcon: http://www.abhisheksur.com/2012/08/notifyicon-with-wpf-applications.html
更先进的解决方案,基于 NotifyIcon 的新库具有更多功能: http://www.codeproject.com/Articles/36468/WPF-NotifyIcon
有关 NotifyIcon 的更多信息可以在这里找到: http://msdn.microsoft.com/en-us/library/system.windows.forms.notifyicon.aspx
您可以在 App.xaml.cs 中设置 NotifyIcon 的代码
using System.Drawing;
namespace DDD
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
System.Windows.Forms.NotifyIcon nIcon = new System.Windows.Forms.NotifyIcon();
public App()
{
nIcon.Icon = new Icon(@"path to ico");
nIcon.Visible = true;
nIcon.ShowBalloonTip(5000, "Title", "Text", System.Windows.Forms.ToolTipIcon.Info);
nIcon.Click += nIcon_Click;
}
void nIcon_Click(object sender, EventArgs e)
{
//events comes here
MainWindow.Visibility = Visibility.Visible;
MainWindow.WindowState = WindowState.Normal;
}
}
}
在您的 Mainwindow.xaml.cs 中:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
this.Visibility = Visibility.Hidden;
}
确保 Window_Closing 绑定到主窗口的关闭事件。
如果您“关闭”主窗口,窗口可见性将设置为隐藏,但您的应用程序仍将运行。 只需单击通知区域中的 NotifyIcon,即可返回窗口。
编辑:
有一种非常简单但功能强大的方法可以通过 Windows 通知中心显示
toast
消息。
Sinds Windows 10,这是显示通知的最常见方式,不再通过 ShowBalloonTip
。
更多信息可以在这里找到。
是的,这是可能的,并且我在我的个人项目中成功地使用了它。 有一个由 Philip Sumi 编写的优秀控件http://www.hardcodet.net/projects/wpf-notifyicon。我正是使用了那个,它效果非常好,看起来也不错(主观)。
请注意:请注意许可条款,检查您是否可以在您的项目中使用它。