WPF应用程序最小到系统托盘
WPF应用程序最小到系统托盘
此内容年代久远,谨慎参考

当前 WPF 并不提供原生方法注册托盘,只能借助 Winforms 的组件实现,也可以使用 Win32 但太麻烦了

csharppublic partial class MainWindow:Window{
  private NotifyIcon mNotifyIcon;

  public MainWindow(){
      InitializeComponent();

      this.mNotifyIcon=new NotifyIcon();
      this.mNotifyIcon.BalloonTipText="应用程序托盘";
      this.mNotifyIcon.ShowBalloonTip(2000);
      this.mNotifyIcon.Text="应用程序托盘";
      this.mNotifyIcon.Visible=true;
      //从exe文件读取位图资源
      this.mNotifyIcon.Icon=System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
      //打开菜单项
      System.Windows.Forms.MenuItem open=new System.Windows.Forms.MenuItem("Open");
      open.Click += new EventHandler(Show);
      //退出菜单项
      System.Windows.Forms.MenuItem exit=new System.Windows.Forms.MenuItem("Exit");
      exit.Click += new EventHandler(Close);
      //关联托盘控件
      System.Windows.Forms.MenuItem[] childen=new System.Windows.Forms.MenuItem[]{open,exit};
      this.mNotifyIcon.ContextMenu=new System.Windows.Forms.ContextMenu(childen);
      //鼠标双击事件
      this.mNotifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler((sender,event)=>{
          if(event.Button!=MouseButtons.Left){return;}
          this.Show(sender,event);
      });
  }

  private void Show(object sender, EventArgs e){
      this.Visibility=System.Windows.Visibility.Visible;
      this.ShowInTaskbar=true;
      this.Activate();
  }

  private void Hide(object sender, EventArgs e){
      this.ShowInTaskbar=false;
      this.Visibility=System.Windows.Visibility.Hidden;
  }

  private void Close(object sender, EventArgs e){
      this.mNotifyIcon.Visible=false;//避免托盘绘图缓存
      System.Windows.Application.Current.Shutdown();
  }
}
作者
ragnaroks
发布时间
2015-02-20
创作协议