WPF中使用NotifyIcon(系統(tǒng)托盤)
說明:本文基于 .Netcore 3.X
一、啟用System.Windows.Forms
因系統(tǒng)托盤功能模塊,定義在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();
? ? ? ?//系統(tǒng)托盤顯示
? ? ? ?this.notifyIcon = new NotifyIcon();
? ? ? ?this.notifyIcon.BalloonTipText = "系統(tǒng)監(jiān)控中... ...";
? ? ? ?this.notifyIcon.ShowBalloonTip(2000);
? ? ? ?this.notifyIcon.Text = "系統(tǒng)監(jiān)控中... ...";
? ? ? ?//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);
**歡迎大家留言交流**