C#中NotifyIcon控件应用实例
NotifyIcon控件
1.功能
NotifyIcon控件通常用于显示在后台运行的进程的图标,这些进程大部分时间不显示用户界面。每个NotifyIcon控件都在状态栏区域显示一个图标。如果有3个后台进程,并希望为每个后台进程各显示一个图标,则需要添加3个NotifyIcon控件。图1所示为NotifyIcon控件。

图1 NotifyIcon控件
2.属性
NotifyIcon控件常用属性及说明如表1所示。

表1 NotifyIcon控件常用属性及说明
下面对比较重要的属性进行详细介绍。
(1)Visible属性。
语法:
public bool Visible { get; set; }
属性值:如果图标在通知区域中可见,则为True;否则为False。默认值为False。
(2)BalloonTipIcon属性。
语法:
public ToolTipIcon BalloonTipIcon { get; set; }
属性值:要显示在与NotifyIcon关联的气球提示上的ToolTipIcon。
示例
BalloonTipIcon属性设置
本示例中,当程序运行时,在窗体中单击鼠标右键,弹出一个“退出”快捷菜单,同时在状态栏中显示一个小人图标。示例运行结果如图2所示。

图2 BalloonTipIcon属性效果
程序主要代码如下:
notifyIcon1.Visible = True;
完整程序代码如下:
★★★★★主程序文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace _8_12
{
static class Program
{
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmNotifyIcon());
}
}
}
★★★★★frmNotifyIcon窗体设计文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace _8_12
{
public partial class frmNotifyIcon : Form
{
public frmNotifyIcon()
{
InitializeComponent();
}
private void frmNotifyIcon_Load(object sender, EventArgs e)
{
notifyIcon1.Visible = true;
}
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
}
private void 退出EToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
★★★★★frmNotifyIcon窗体代码文件完整程序代码★★★★★
namespace _8_12
{
partial class frmNotifyIcon
{
///
/// 必需的设计器变量。
///
private System.ComponentModel.IContainer components = null;
///
/// 清理所有正在使用的资源。
///
/// 如果应释放托管资源,为 true;否则为 false。
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
///
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
///
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmNotifyIcon));
this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.退出EToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.label1 = new System.Windows.Forms.Label();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
//
// notifyIcon1
//
this.notifyIcon1.ContextMenuStrip = this.contextMenuStrip1;