学习目标:
记录从WPF应用创建开始,一步步到任务栏图标创建的全过程。流程:
1、环境:Win10 + VS2017
打开VS2017,选择文件 -> 新建 -> 项目 -> Visual C# -> Windows桌面 ->WPF应用 -> 更改项目名为 TasbarIcon -> 确定

2、添加图标类
右键项目 -> 添加 ->引用,找到System.Windows.Forms 和 System.Drawing两个程序集,打上勾添加进去。

双击打开App.xaml.cs文件,在 namespace TaskbarIcon 里面添加图标类代码
//App.xaml.cs
namespace TaskbarIcon
{public partial class App : Application{}public class myIcon{//任务栏图标System.Windows.Forms.NotifyIcon notifyIcon = null;public void Icon(){//创建图标this.notifyIcon = new System.Windows.Forms.NotifyIcon();//程序打开时任务栏会有小弹窗this.notifyIcon.BalloonTipText = "PalmServer is running...";//鼠标放在图标上时显示的文字this.notifyIcon.Text = "PalmServer";//图标图片的位置,注意这里要用绝对路径this.notifyIcon.Icon = new System.Drawing.Icon("E:/WPF prroject/WpfApp4/WpfApp4/sheep.ico");//显示图标this.notifyIcon.Visible = true;//右键菜单--退出菜单项System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("Quit");exit.Click += new EventHandler(CloseWindow);//关联托盘控件System.Windows.Forms.MenuItem[] children = new System.Windows.Forms.MenuItem[] { exit };notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(children);this.notifyIcon.ShowBalloonTip(1000);}//退出菜单项对应的处理方式public void CloseWindow(object sender, EventArgs e){//Dispose()函数能够解决程序退出后图标还在,要鼠标划一下才消失的问题this.notifyIcon.Dispose();//关闭整个程序Application.Current.Shutdown();}}
}
3、使用图标类
先打开 MainWindow.xaml文件,在里面添加closed事件的声明
//MainWindow.xaml
<Window x:Class="TaskbarIcon.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:TaskbarIcon"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"Closed="Window_Closed"><Grid></Grid>
</Window>
然后在MainWindo.xaml.cs文件里面使用图标类
//MainWindo.xaml.cs
namespace TaskbarIcon
{public partial class MainWindow : Window{public MainWindow(){InitializeComponent();ic = new myIcon();ic.Icon();}myIcon ic;public void Window_Closed(object sender, EventArgs e){ic.CloseWindow(null, null);System.Windows.Application.Current.Shutdown();}}
}
至此,就能创建出自己的程序任务栏图标了!











