2步完成:
1、在任务栏上增加一个本程序正在运行的图标菜单,并且鼠标点击后弹出打开和关闭菜单,打开可以打开一个窗口。关闭则退出。
实现方式如下:
using System.Windows;
using System.Windows.Forms;
using Application = System.Windows.Application;
namespace WpfApp1
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
private NotifyIcon notifyIcon;
private MainWindow mainWindow;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// 创建 NotifyIcon 对象
notifyIcon = new NotifyIcon();
notifyIcon.Icon = new System.Drawing.Icon("res\\icons\\MaterialDesignIcons\\account-clock1.ico");
notifyIcon.Text = "My Application";
notifyIcon.Visible = true;
mainWindow = new MainWindow();
mainWindow.Show();
mainWindow.Hide();
// 添加菜单项
var openMenuItem = new MenuItem("Open");
openMenuItem.Click += (s, e1) => {
//var mainWindow = new MainWindow();
mainWindow.Show();
};
var closeMenuItem = new MenuItem("Close");
closeMenuItem.Click += (s, e2) => {
Shutdown();
};
var contextMenu = new ContextMenu(new[] { openMenuItem, closeMenuItem });
notifyIcon.ContextMenu = contextMenu;
// 将应用程序退出事件绑定到 NotifyIcon 对象
Exit += (s, e3) => {
notifyIcon.Dispose();
notifyIcon = null;
};
}
}
}
2、窗口最小化时隐藏窗口:在 MainWindow.xaml.cs 中,添加以下代码来处理窗口最小化事件:
private void Window_StateChanged(object sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
Hide();
}
}