WPF程序最小化至系统托盘
作者:互联网
1 using System; 2 using System.Windows; 3 using System.Windows.Forms; 4 5 namespace STExamClientService 6 { 7 /// <summary> 8 /// MainWindow.xaml 的交互逻辑 9 /// </summary> 10 public partial class MainWindow : Window 11 { 12 NotifyIcon notifyIcon; 13 public MainWindow() 14 { 15 InitializeComponent(); 16 17 this.notifyIcon = new NotifyIcon(); 18 this.notifyIcon.Text = "xxx系统";//鼠标移入图标后显示的名称 19 this.notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath); 20 this.notifyIcon.Visible = true; 21 //打开菜单项 22 MenuItem show = new MenuItem("显示主窗体"); 23 show.Click += new EventHandler(Show); 24 //退出菜单项 25 MenuItem exit = new MenuItem("退出"); 26 exit.Click += new EventHandler(Close); 27 //关联托盘控件 28 MenuItem[] mis = new MenuItem[] { show, exit }; 29 notifyIcon.ContextMenu = new ContextMenu(mis); 30 31 this.notifyIcon.MouseDoubleClick += new MouseEventHandler((o, e) => 32 { 33 if (e.Button == MouseButtons.Left) 34 { 35 this.Show(o, e); 36 } 37 }); 38 } 39 /// <summary> 40 /// 显示窗体 41 /// </summary> 42 /// <param name="sender"></param> 43 /// <param name="e"></param> 44 private void Show(object sender, EventArgs e) 45 { 46 this.ShowInTaskbar = true; 47 this.WindowState = WindowState.Normal; 48 this.Activate(); 49 } 50 /// <summary> 51 /// 关闭窗体 52 /// </summary> 53 /// <param name="sender"></param> 54 /// <param name="e"></param> 55 private void Close(object sender, EventArgs e) 56 { 57 System.Windows.Application.Current.Shutdown(); 58 } 59 /// <summary> 60 /// 窗体状态改变 61 /// </summary> 62 /// <param name="sender"></param> 63 /// <param name="e"></param> 64 private void Window_StateChanged(object sender, EventArgs e) 65 { 66 //判断是否选择的是最小化按钮 67 if (this.WindowState == WindowState.Minimized) 68 { 69 //隐藏任务栏区图标 70 this.ShowInTaskbar = false; 71 //图标显示在托盘区 72 this.notifyIcon.Visible = true; 73 } 74 } 75 } 76 }
XAML
1 <Window x:Class="STExamClientService.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:STExamClientService" 7 mc:Ignorable="d" 8 Title="xxx系统" Height="450" Width="800" WindowStartupLocation="CenterScreen" StateChanged="Window_StateChanged" > 9 <Grid/> 10 </Window>
标签:notifyIcon,系统托盘,System,WindowState,MenuItem,窗体,最小化,new,WPF 来源: https://www.cnblogs.com/Ladon/p/14717912.html