制作托盘程序的关键是VS里面的NotifyIcon控件
这个小例子使窗体最大化和最小化按钮隐藏,关闭按钮失效成为隐藏按钮,双击托盘图标显示主窗体,右键点击弹出菜单
1、
在C#界面拖出一个notifyIcon1,设置相关属性(我是初学者),或者在代码里面写
3个Balloon*属性分别是托盘气泡的图标、内容、标题(例如用在下面的FormClosing事件)
ContextMenuStrip属性是下面将要用到的右键托盘图标时关联的弹窗
Icon属性就是给托盘添加图标
Text属性是当鼠标停留在托盘图标时的提示信息。
2、
在界面拖出一个contextMenuStrip1并添加“嘿嘿”和“退出”
全部代码:
using System;
using System.Collections.Generic;using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace test
{
public partial class Form16托盘 : Form
{
public Form16托盘()
{
InitializeComponent();
}
private void Form16托盘_Load(object sender, EventArgs e)
{
//this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
this.MaximizeBox = false;
this.MinimizeBox = false;
}
private void 嘿嘿ToolStripMenuItem_Click(object sender, EventArgs e)
{
//this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Show();
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
notifyIcon1.Dispose();//释放托盘资源
Application.Exit();//释放所有资源
}
private void Form16托盘_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
this.Hide();
notifyIcon1.BalloonTipTitle = "Title";
notifyIcon1.BalloonTipText = "程序还在继续运行......" + "\r\n" + "单击托盘图标还原窗口.";
notifyIcon1.ShowBalloonTip(2000);
}
}
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
this.Show();
}
}
}
转载e.CloseReason属性
if (e.CloseReason != System.Windows.Forms.CloseReason.WindowsShutDown)
{
}
e.CloseReason属性,其值为CloseReason枚举类型
成员名称 说明
ApplicationExitCall
FormOwnerClosing
MdiFormClosing
None
TaskManagerClosing Microsoft Windows
UserClosing
WindowsShutDown