WinForm设置任务栏托盘程序
程序设计界面如下图所示:
1.在程序初始化加载的时候设置程序图标,具体code如下:
private void Form1_Load(object sender, EventArgs e) { //this.ShowInTaskbar = false; //this.WindowState = FormWindowState.Minimized; string startUp = Application.ExecutablePath; int pp = startUp.LastIndexOf("\\"); startUp = startUp.Substring(0,pp); string icon = startUp + "\\HHQC.ico"; notifyIcon1.Icon = new Icon(icon); }
2.窗体最小化的时候,在任务栏显示应用程序通知图标,code如下:
private void Form1_SizeChanged(object sender, EventArgs e) { if(this.WindowState == FormWindowState.Minimized){ this.Hide(); this.notifyIcon1.Visible = true; } }
3.设置任务栏图标点击事件(双击显示主界面,右击显示菜单),code如下:
#region 任务栏相关操作 //双击任务栏托盘程序图标-显示主界面 private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { if (this.WindowState == FormWindowState.Minimized) { this.Show(); this.WindowState = FormWindowState.Normal; this.Activate(); } else { this.WindowState = FormWindowState.Minimized; this.Hide(); } } //任务栏右键菜单栏退出 private void toolStripMenu_Exit_Click(object sender, EventArgs e) { //this.Close(); Application.Exit(); } //任务栏右键菜单栏-打开主界面 private void ToolStripMenu_Open_Click(object sender, EventArgs e) { if (this.Visible) { this.Hide(); this.WindowState = FormWindowState.Minimized; } else { this.Show(); this.WindowState = FormWindowState.Normal; } } #endregion
4.用户点击窗体右上角关闭按钮时设置不退出程序,只是最小化到系统托盘,code如下:
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; this.WindowState = FormWindowState.Minimized; notifyIcon1.Visible = true; this.Hide(); return; } }
5.任务栏程序图标右键菜单退出程序或者是在程序主界面窗体菜单中选择退出程序
private void toolStripMenu_Exit_Click(object sender, EventArgs e) { //this.Close(); Application.Exit(); }