[WPF]引用winform中的notifyicon实现托盘图标程序
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2017-08-27 11:14:44
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
使用前先引入winform对应的库
//定义一个变量 private System.Windows.Forms.NotifyIcon notifyIcon;
然后加入下面代码,程序初始化的时候调用 InitNotifyIcon
private void InitNotifyIcon() { this.notifyIcon = new System.Windows.Forms.NotifyIcon(); this.notifyIcon.BalloonTipText = "... ..."; this.notifyIcon.ShowBalloonTip(2000); this.notifyIcon.Text = "... ..."; this.notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath); this.notifyIcon.Visible = true; //打开菜单项 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 }; notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen); this.notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler((o, e) => { if (e.Button == System.Windows.Forms.MouseButtons.Left) this.Show(o, e); }); } 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) { System.Windows.Application.Current.Shutdown(); }
关闭的时候最小化隐藏
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { this.ShowInTaskbar = false; this.WindowState = WindowState.Minimized; e.Cancel = true; }