WPF应用程序最小到系统托盘

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

public 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();
    }
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!