> 文章列表 > WPF 程序最小化到托盘

WPF 程序最小化到托盘

WPF 程序最小化到托盘

WPF 程序最小化到托盘

一.使用的是WinForms的NotifyIcon控件

  1. 添加WinForm引用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Qqm4lvzY-1677652141280)(C:\\Users\\Administrator\\AppData\\Roaming\\Typora\\typora-user-images\\image-20230301141302314.png)]

二.使用NotifyIcon控件

  1. 添加引用

    using WinForms = System.Windows.Forms;
    
  2. 全局引用

    private WinForms.NotifyIcon MyNotifyIcon;
    private WinForms.ContextMenu NotifyMenu;
    private WinForms.MenuItem ItemWindow;
    private WinForms.MenuItem ItemClose;
    
  3. 在软件开始启动NotifyIcon

    NotifyMenu = new WinForms.ContextMenu();//可自定义Item,这边只做了主界面和关闭两个选项ItemWindow = new WinForms.MenuItem() { Text = "主界面" };ItemClose = new WinForms.MenuItem() { Text = "关闭" };WinForms.MenuItem[] menuItems = new WinForms.MenuItem[] { ItemWindow, ItemClose };NotifyMenu.MenuItems.AddRange(menuItems);ItemWindow.Click += _openWindow_Click;ItemClose.Click += _closeApp_Click;MyNotifyIcon = new WinForms.NotifyIcon(new System.ComponentModel.Container());//注意这里要写对图片的路径地址MyNotifyIcon.Icon = new System.Drawing.Icon(@"../../logo.ico");MyNotifyIcon.Text = "托盘测试程序";MyNotifyIcon.Visible = true;MyNotifyIcon.MouseDoubleClick += _notifyIcon_MouseDoubleClick;MyNotifyIcon.ContextMenu = NotifyMenu;
    
    • 响应回调代码

      private void _notifyIcon_MouseDoubleClick(object sender, WinForms.MouseEventArgs e){this.Show();}private void _openWindow_Click(object sender, EventArgs e){this.Show();}private void _closeApp_Click(object sender, EventArgs e){closeApp();}private void closeApp(){IsCloseApp = true;MyNotifyIcon.Dispose();this.Close();System.Windows.Application current = System.Windows.Application.Current;if (current != null) current.Shutdown();}
      

三.监控关闭界面

  1. 界面的关闭回调

    this.Closed += Window_Closed;
    this.Closing += Window_Closing;
    
  2. 回调代码

    private void Window_Closed(object sender, EventArgs e){if (!IsCloseApp){MyNotifyIcon.Dispose();}}private void Window_Closing(object sender, CancelEventArgs e){if (!IsCloseApp){this.Hide();e.Cancel = true;}}
    

{
this.Hide();
e.Cancel = true;
}
}