1.拉出一个notifyIcon1到用户界面,也可以NEW一个
2.拉出一个ContextMenuStrip控件,命名为mymenu,集合中增加退出
3.notifyIcon1的属性ContextMenuStrip 增加 myMenu;或者this.notifyIcon1.ContextMenuStrip = myMenu;
private void FrmMain_Load(object sender, EventArgs e)
{
//最小化到托盘
// this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
// notifyIcon1.Icon = new Icon("2221.ico");//指定一个图标
notifyIcon1.Visible = false;
notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick);
this.SizeChanged += new System.EventHandler(this.FrmMain_SizeChanged);
}
/// <summary>
/// 窗体大小改变事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FrmMain_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)//最小化
{
this.ShowInTaskbar = false;
this.notifyIcon1.Visible = true;
}
}
/// <summary>
/// 关闭窗体事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult result = MessageBox.Show("是否退出?选否,最小化到托盘", "操作提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
this.Dispose();
Application.Exit();
}
else
{
e.Cancel = true;
this.WindowState = FormWindowState.Minimized;
this.Visible = false;
this.notifyIcon1.Visible = true;
}
}
/// <summary>
/// 最小化图标鼠标事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
myMenu.Show();
}
}
/// <summary>
/// 退出事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Dispose();
Application.Exit();
}
效果