Hardcodet.NotifyIcon.Wpf.NetCore
最近折腾.NET 5方面的东西,实现wpf托盘功能上却犯了难,原来的开发套路在这里用不上。 开发过程中并不能像.NET farmework 那样直接引用winform的 System.Windows.Forms .dll 来实现功能,最后找到了一个开源库 Hardcodet.NotifyIcon.Wpf.NetCore最终实现了我想要的效果。
在.NET core.NET 5 下WPF实现托盘图标功能
在.NET core.NET 5 下WPF利用三方控件“Hardcodet.NotifyIcon.Wpf.NetCore”实现托盘图标功能
nuget引用开源程序包 Hardcodet.NotifyIcon.Wpf.NetCore
创建托盘图标核心代码
我这里将代码封装成了静态方法 方便外部调用
public static class WindowsTaskbarIcon
{
static TaskbarIcon WindowsNotifyIcon { get; set; }
public static void Open()
{
if (WindowsNotifyIcon is null)
{
InitNotifyIcon();
}
}
public static void Exit()
{
if (WindowsNotifyIcon is null) return;
WindowsNotifyIcon.Visibility = System.Windows.Visibility.Collapsed;
WindowsNotifyIcon.Dispose();
}
///初始化托盘控件
static void InitNotifyIcon()
{
WindowsNotifyIcon = new TaskbarIcon();
WindowsNotifyIcon.Icon = new System.Drawing.Icon("yuantk.ico");
ContextMenu context = new ContextMenu();
MenuItem show = new MenuItem();
show.Header = "主页";
show.Click += delegate (object sender, RoutedEventArgs e)
{
Application.Current.MainWindow.Show();
Application.Current.MainWindow.Topmost = true;
Application.Current.MainWindow.Topmost = false;
};
context.Items.Add(show);
MenuItem exit = new MenuItem();
exit.Header = "退出";
exit.Click += delegate (object sender, RoutedEventArgs e)
{
Environment.Exit(0);
};
context.Items.Add(exit);
WindowsNotifyIcon.ContextMenu = context;
}
}
程序启动函数里启用
使用起来也很简单 直接在App.Xaml.cs 启动函数方法内 执行 WindowsTaskbarIcon.Open() 即可**