1.WPF程序在XAML文件中设置任务栏图标
<Window x:Class="ShAirportDataSync.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:ShAirportDataSync" mc:Ignorable="d" Title="窗体标题" Icon="logo_64X64.ico" Height="500" Width="850"> <!--使用Window的Icon属性设置图标--> <Grid> ****** </Grid> </Window>
2.WPF程序设置通知栏图标
NotifyIcon notifyIcon; public MainWindow() { InitializeComponent(); //图标 notifyIcon = new NotifyIcon(); //notifyIcon.Icon = new System.Drawing.Icon("NotifyIcon.ico"); notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath); notifyIcon.BalloonTipText = "提示文字****"; notifyIcon.ShowBalloonTip(3000); notifyIcon.Visible = true; }
3.WPF程序通知栏右键菜单
//图标右键菜单 notifyIcon.ContextMenu = new ContextMenu(new [] { new MenuItem("隐藏窗体", (sender, args) => { Visibility = System.Windows.Visibility.Hidden; ShowInTaskbar = false; }), new MenuItem("打开窗体", (sender, args) => { Visibility = System.Windows.Visibility.Visible; ShowInTaskbar = true; Activate(); }), new MenuItem("退出程序", (sender, args) => { System.Windows.Application.Current.Shutdown(); }) }); //双击通知栏图标 notifyIcon.MouseDoubleClick += (sender, args) => { Visibility = System.Windows.Visibility.Visible; ShowInTaskbar = true; Activate(); };
4.关闭WPF窗体到后台运行
protected override void OnClosing(CancelEventArgs e) { //取消关闭窗体 e.Cancel = true; //将窗体变为最小化 this.WindowState = WindowState.Minimized; //不显示在系统任务栏 this.ShowInTaskbar = false; }