WPF 最小化到系统托盘

发布于:2025-02-11 ⋅ 阅读:(36) ⋅ 点赞:(0)

只需要在MainWindow的后台复制下方代码即可

最小化托盘  导一个系统自带System.Drawing
 public partial class MainWindow : Window
 {
     private NotifyIcon trayIcon;
     public MainWindow()
     {

         InitializeComponent();
         trayIcon = new NotifyIcon();
         trayIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
         trayIcon.Visible = true;
         trayIcon.ContextMenu = new System.Windows.Forms.ContextMenu(new System.Windows.Forms.MenuItem[]
         {
             new System.Windows.Forms.MenuItem("恢复", OnRestoreClick),
             new System.Windows.Forms.MenuItem("退出", OnExitClick)
         });
         this.StateChanged += MainWindow_StateChanged;
    
     }


     private void MainWindow_StateChanged(object sender, EventArgs e)
     {
         if (this.WindowState == WindowState.Minimized)
         {
             this.Hide();
             trayIcon.Visible = true;
         }
     }

   
     private void OnRestoreClick(object sender, EventArgs e)
     {
         this.Show();
         this.WindowState = WindowState.Normal;
         trayIcon.Visible = false; 
     }

     // 点击托盘图标的退出操作
     private void OnExitClick(object sender, EventArgs e)
     {
         trayIcon.Visible = false;  
         System.Windows.Application.Current.Shutdown();  
     }

     // 处理窗口关闭事件
     protected override void OnClosed(EventArgs e)
     {
         base.OnClosed(e);
         trayIcon.Dispose(); 
     }

 }