csharp将关闭程序后最小化,并且在在托盘中显示图标,右键图标显示退出和主界面两个菜单,点击其他地方关闭二级菜单
时间: 2024-05-14 17:13:10 浏览: 195
可以使用以下代码实现:
```csharp
public partial class MainForm : Form
{
private NotifyIcon notifyIcon;
public MainForm()
{
InitializeComponent();
// 创建托盘图标
notifyIcon = new NotifyIcon();
notifyIcon.Icon = this.Icon;
notifyIcon.Visible = true;
notifyIcon.MouseClick += NotifyIcon_MouseClick;
}
// 窗口关闭时最小化到托盘
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
this.Hide();
}
base.OnFormClosing(e);
}
// 托盘图标点击事件
private void NotifyIcon_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// 左键单击时显示主界面
this.Show();
}
else if (e.Button == MouseButtons.Right)
{
// 右键单击时显示菜单
ContextMenuStrip menu = new ContextMenuStrip();
menu.Items.Add("主界面", null, (s, arg) => { this.Show(); });
menu.Items.Add("退出", null, (s, arg) => { Application.Exit(); });
notifyIcon.ContextMenuStrip = menu;
menu.Show(Control.MousePosition);
}
}
}
```
在窗口关闭时,判断关闭原因是否为用户关闭,如果是,则取消关闭操作并将窗口隐藏。在托盘图标的鼠标点击事件中,左键单击时显示主界面,右键单击时显示菜单,并在菜单中添加“主界面”和“退出”两个选项。当菜单显示时,点击其他地方会自动关闭。
阅读全文