用C#为Shell托盘图标设置动画






2.75/5 (17投票s)
这个类可以帮助动画化托盘图标。
引言
本文解释了如何动画化托盘图标。在 .NET 中,添加托盘图标的操作已经大大简化。
在编写应用程序时,很多情况下我们需要将应用程序添加到系统托盘,并且大部分常用功能将通过系统托盘的上下文菜单提供。应用程序将通过图标动画显示后台处理过程,例如,如果应用程序正在处理事件,则会在事件处理完成之前动画化图标。
背景
如果您正在使用 C# 编写应用程序,它具有 NotifyIcon()
组件,该组件具有将应用程序图标添加到系统托盘的功能,或者您可以使用 Shell API Shell_NotifyIcon()
来添加图标;虽然使用 API 并不容易。
关于 SystemTray 类
这个类封装了 NotifyIcon
组件的几乎所有功能,并扩展了功能以实现托盘图标的轻松动画。该类提供了一些函数,可以轻松配置该类。
SystemTray 类摘要
使用这个类非常简单。我将在解释类的所有其他细节之后,描述如何使用该类。
构造函数
语法
这个类提供了四个构造函数,以简化在您的项目中对该类的使用。
//Default constructor
SystemTray()
//Constructor with the parameter tooltip text
SystemTray(string pTrayText)
//Constructor with tooltip test and icon
SystemTray(string pTrayText, Icon pIcon)
//Constructor with Animation parameter
SystemTray(string pTrayText,Icon pIcon,bool pAnimate)
参数详情
pTrayText
:当鼠标指向应用程序系统托盘图标时,您希望显示的工具提示文本字符串。pIcon
:将在系统托盘中显示的System.Drawing.Icon
对象。pAnimate
:一个bool
参数,用于支持动画功能。
方法
语法
//Start the icon animation
void StartAnimation()
//Stops the icon animation
void StopAnimation()
//Starts the animation with the timeout value after
//which the animation will stop.value will be in miliseconds
void StartAnimation(int timeOut)
//Displays the baloon tooltip with timeout value.
//Time out will be in miliseconds
void ShowBaloonTrayTip(int nTimeout)
//Displays the baloon tooltip with some parameters
void ShowBaloonTrayTip(int nTimeOut,string tipTitle,
string tipText,ToolTipIcon tipIcon)
//Sets the icon objets to the class,will be used for animation
void SetIconRange(object[] IconList)
属性
//Set icon to class
Icon Icon
//Make tray icon visible true or false
bool Visible
//Set text to trayicon
string TrayText
//Sets the animation ability
bool Animate
//To set the baloon tooltip text
string BaloonTipText
//To set the baloon tooltip title
string BalloonTipTitle
//To set the baloon tooltip icon
ToolTipIcon BalloonTipIcon
使用 SystemTray 类
以下是如何使用 SystemTray
类
//SystemTray stray;
//Add in form load or InitializeComponent() function
object[] objValues = new object[2];
objValues[0] = Convert.ToString("Icon1.ico");
objValues[1] = Convert.ToString("Icon2.ico");
//Add Icon
stray= new SystemTray("Sample Tray Icon Animation",null,true);
//Sets icons for animation
stray.SetIconRange(objValues);
//Set menu
stray.SetContextMenuOrStrip((object)contextMenuStrip1);
//Set Event
stray.DoubleClick += new System.EventHandler(this.DbClick);
//Set menu handler
stray.ContextMenuStrip.Items[0].Click +=
new EventHandler(SystemTraySample_Click);
//Start icon animation for 2 seconds
stray.StartAnimation(2000);