首先,先拖一个NotifyIcon到主窗体,然后设置NotifyIcon的图标,不然等下最小化后,都找不到那个程序了,还有那个Text也是,不写名字,就默认是NotifyIcon了..如下图:
然后双击NotifyIcon,代码如下:
/// <summary>
/// 添加双击托盘图标事件(双击显示窗口)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
//还原窗体显示
WindowState = FormWindowState.Normal;
//激活窗体并给予它焦点
this.Activate();
//任务栏区显示图标
this.ShowInTaskbar = true;
//托盘区图标隐藏
notifyIcon1.Visible = false;
}
}
然后分别到主窗口的单击事件里面添加以下两个方法即可,如下图:
代码如下:
/// <summary>
/// 判断是否最小化,然后显示托盘
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void F_Main_SizeChanged(object sender, EventArgs e)
{
//判断是否选择的是最小化按钮
if (WindowState == FormWindowState.Minimized)
{
//隐藏任务栏区图标
this.ShowInTaskbar = false;
//图标显示在托盘区
notifyIcon1.Visible = true;
}
}
/// <summary>
/// 确认是否退出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void F_Main_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("是否确认退出程序?", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
// 关闭所有的线程
this.Dispose();
this.Close();
}
else
{
e.Cancel = true;
}
}
下面是托盘右键菜单的制作:
先拖一个ContextMenuStrip到主界面,然后添加你的右键菜单,在然后绑定给NotifyIcon即可,图形如代码如下:
绑定菜单给NotifyIcon
后台代码:
/// <summary>
/// 托盘右键显示主界面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Normal;
}
/// <summary>
/// 托盘右键退出程序
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBox.Show("是否确认退出程序?", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
// 关闭所有的线程
this.Dispose();
this.Close();
}
}