在.NET core\.NET 5 下WPF如何实现托盘图标功能
.NET5wpf托盘图标
编程开发
1226
在.NET core.NET 5 下WPF利用三方控件“Hardcodet.NotifyIcon.Wpf.NetCore”实现托盘图标功能
最近折腾.NET 5方面的东西,实现wpf托盘功能上却犯了难,原来的开发套路在这里用不上。 开发过程中并不能像.NET farmework 那样直接引用winform的 System.Windows.Forms .dll 来实现功能,最后找到了一个开源库最终实现了我想要的效果。
以下是实现过程
1、nuget引用开源程序包 Hardcodet.NotifyIcon.Wpf.NetCore
2、 后台代码 我这里封装成了静态方法
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;
}
}
3、 使用起来也很简单 直接在App.Xaml.cs 启动函数方法内 执行 WindowsTaskbarIcon.Open() 即可
4、运行效果