private NotifyIcon _notifyIcon;//托盘控件
private ContextMenuStrip _nfmenuStrip;//右键快捷菜单//初始化托盘
private void InitialTray()
{_nfmenuStrip = new ContextMenuStrip();_nfmenuStrip.Items.Add("退出", null, Exit_Click);_notifyIcon = new NotifyIcon();_notifyIcon.ContextMenuStrip = _nfmenuStrip;//关键快捷菜单_notifyIcon.Visible = true;//托盘图标可见_notifyIcon.Text = "";//名称_notifyIcon.BalloonTipTitle = "";_notifyIcon.BalloonTipText = "";_notifyIcon.BalloonTipIcon = ToolTipIcon.Info;_notifyIcon.MouseDoubleClick += notifyIcon_MouseDoubleClick;_notifyIcon.Icon = GetIconByResource("命名空间");
}private Icon GetIconByResource(string name)
{var assembly = Assembly.GetExecutingAssembly();var stream = assembly.GetManifestResourceStream(name);Icon ico = new Icon(stream);return ico;
}private void notifyIcon_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
{if(e.Button == MouseButtons.Left){if(this.Visibility != Visibility.Hidden){this.WindowState = WindowState.Normal;this.Visibility = Visibility.Visible;this.Activate();}else{this.Visibility = Visibility.Visible;this.Activate();}}
}//快捷菜单-》退出按钮事件
private void Exit_Click(object sender, EventArgs e)
{_notifyIcon.Visible = false;//托盘图片不可见Application.Current.Shutdown();//退出程序
}//窗体关闭按钮事件
private void CloseBtn_Click(object sender, RoutedEventArgs e)
{this.Hide();this.Visibility = Visibility.Hidden;_notifyIcon.ShowBalloonTip(1);
}//窗体最小化按钮事件
private void MinBtn_Click(object sender, RoutedEventArgs e)
{this.WindowState = WindowState.Minimized;this.Visibility = Visibility.Visible;
}