包含点击关闭按钮后最小化系统托盘,点击系统托盘图标后自动弹出窗口,点击托盘右键菜单退出
public partial class MainWindow : Window
{
private readonly System.Windows.Forms.NotifyIcon nIcon = new System.Windows.Forms.NotifyIcon();
public MainWindow()
{
InitializeComponent();
initNotifyIcon();
}
private void initNotifyIcon()
{
nIcon.Visible = true;
nIcon.Icon = new Icon("./favicon.ico");
nIcon.Text = "测试程序";
nIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(show_Click);
nIcon.ContextMenu = new System.Windows.Forms.ContextMenu();
System.Windows.Forms.MenuItem show = new System.Windows.Forms.MenuItem("打开");
show.Click += new EventHandler(show_Click);
nIcon.ContextMenu.MenuItems.Add(show);
System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("退出");
exit.Click += new EventHandler(exit_Click);
nIcon.ContextMenu.MenuItems.Add(exit);
}
private void exit_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void show_Click(object Sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
WindowState = WindowState.Normal;
Show();
Activate();
}
protected override void OnStateChanged(EventArgs e)
{
if (WindowState == WindowState.Minimized) Hide();
base.OnStateChanged(e);
}
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
Hide();
base.OnClosing(e);
}
}