欢迎光临散文网 会员登陆 & 注册

WPF中使用NotifyIcon(系统托盘)

2020-04-15 09:13 作者:Tuple_元组  | 我要投稿

说明:本文基于 .Netcore 3.X

一、启用System.Windows.Forms

因系统托盘功能模块,定义在System.Windows.Forms.NotifyIcon 中,故需使用System.Windows.Forms。具体方式是在项目文件中,添加“<UseWindowsForms>”内容。

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
  <PropertyGroup>
       <OutputType>WinExe</OutputType>
       <TargetFramework>netcoreapp3.1</TargetFramework>
       <UseWPF>true</UseWPF>
       <UseWindowsForms>true</UseWindowsForms>
       <ApplicationIcon>AppRes\Images\App.ico</ApplicationIcon>
  </PropertyGroup>
</Project>

二、在主窗体中添加如下代码

1.初始化NotifyIcon控件

public MainWindow()
   {
       InitializeComponent();
       //系统托盘显示
       this.notifyIcon = new NotifyIcon();
       this.notifyIcon.BalloonTipText = "系统监控中... ...";
       this.notifyIcon.ShowBalloonTip(2000);
       this.notifyIcon.Text = "系统监控中... ...";
       //this.notifyIcon.Icon = new System.Drawing.Icon(@"AppIcon.ico");
       this.notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
       this.notifyIcon.Visible = true;
       //托盘右键菜单项
       this.notifyIcon.ContextMenuStrip = new ContextMenuStrip();
       this.notifyIcon.ContextMenuStrip.Items.Add("显示主窗口", null, (sender, eventArgs) => {
           this.Visibility = System.Windows.Visibility.Visible;
           this.ShowInTaskbar = true;
           this.Activate();
       });
       this.notifyIcon.ContextMenuStrip.Items.Add("关闭程序", null, (sender, eventArgs) => {
           this.notifyIcon.Dispose();
           System.Windows.Application.Current.Shutdown(0);
       });
       //托盘双击响应
       this.notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler((o, e) =>
        {
           if (e.Button == MouseButtons.Left)
               {
                   this.notifyIcon.ContextMenuStrip.Items[0].PerformClick();
               }
       });            
   }

2.在主窗口顶部自定义的工具栏的关闭按钮中添加以下代码

   this.ShowInTaskbar = false;
   this.Visibility = System.Windows.Visibility.Hidden;
   this.notifyIcon.ShowBalloonTip(20, "信息:", "工作平台已隐藏在这儿。", ToolTipIcon.Info);


**欢迎大家留言交流**

WPF中使用NotifyIcon(系统托盘)的评论 (共 条)

分享到微博请遵守国家法律