Click here to Skip to main content
15,867,330 members
Articles / Programming Languages / C#
Article

SystemTrayNotifyIcon with Event Generator

Rate me:
Please Sign up or sign in to vote.
4.87/5 (29 votes)
3 Feb 2003CPOL3 min read 172.5K   5.6K   143   31
This article provides a generic class using which one can easily use a SystemTrayNotifyIcon class with the key functionalities of hiding, showing and animating NotifyIcon and generating events on every changed state of NotifyIcon.

Sample Image - SystemTrayNotifyIcon.gif

Introduction

This is my first article in C#. Here I have tried to provide a generic class that can be used for adding the System Tray Notification property to your C# project. Besides the more common features of any System Tray Notification class (i.e. Hide, Unhide, Animate etc.), this class provides events that are triggered for every change in state of the Notify Icon. My best efforts were to make this class as easy to use as possible and to some extent I am sure I got success but I am waiting for the views of some good critics, which I am sure I will definitely get very soon ;)

Using SytemTrayNotifyIcon class

Step I

Add SystemTrayNotifyIcon.cs in your project.

Step II

Insert the SystemTrayNotification namespace in your project as shown below.

C#
// Step II for using SystemTrayNotifyIcon class in your project
   using SystemTrayNotification;
//

Step III

Declare a reference variable of class SystemTrayNotifyIcon with access modifier of your choice. I am declaring it as private.

C#
// Step III for using SystemTrayNotifyIcon class in your project
   private SystemTrayNotifyIcon m_SysTrayNotify;    
//

Step IV

Now you have to instantiate the above declared reference variable. The best place for this initialization is your main forms constructor. Here you will get five overloaded constructors which you will have to use according to your requirement.

Constructor 1 

C#
// Step IV for using SystemTrayNotifyIcon class in your project
// This is the first constructor, which takes two parameters
// (parameter 1) System.Windows.Forms.Form form 
// (passing reference of main form)
// (parameter 2) bool visible (pass true to show icon 
// in System Tray else false)
   m_SysTrayNotify = new SystemTrayNotification.SystemTrayNotifyIcon(
            this, true);    
//

Constructor  2

C#
// Step IV for using SystemTrayNotifyIcon class in your project
// This is the first constructor, which takes two parameters
// (parameter 1) System.Windows.Forms.Form form 
// (passing reference of main form)
// (parameter 2) bool visible (pass true to show icon 
// in System Tray else false)
// (parameter 3) string toolTip (pass a string to be set
// as tooltip for System Tray Icon)
   m_SysTrayNotify = new SystemTrayNotification.SystemTrayNotifyIcon(
         this, true, "Hoowa!");    
//

Constructor  3

C#
// Step IV for using SystemTrayNotifyIcon class in your project
// This is the first constructor, which takes two parameters
// (parameter 1) System.Windows.Forms.Form form 
// (passing reference of main form)
// (parameter 2) bool visible (pass true to show icon in 
// System Tray else false)
// (parameter 3) string toolTip (pass a string to be set as
// tooltip for System Tray Icon)
// (parameter 4) Icon icon (pass an icon to be set in System Tray)
   m_SysTrayNotify = new SystemTrayNotification.SystemTrayNotifyIcon(
        this, true, "Hoowa!,
        new System.Drawing.Icon("..\\..\\Default Icon\\PakFlag.ico")");    
//

Constructor  4

C#
// Step IV for using SystemTrayNotifyIcon class in your project
// This is the first constructor, which takes two parameters
// (parameter 1) System.Windows.Forms.Form form 
// (passing reference of main form)
// (parameter 2) bool visible (pass true to show icon
// in System Tray else false)
// (parameter 3) string toolTip (pass a string to be set as
// tooltip for System Tray Icon)
// (parameter 4) ContextMenu contextMenu (pass a ContextMenu
// System Tray Notifications)
   m_SysTrayNotify = new SystemTrayNotification.SystemTrayNotifyIcon(
            this, true, "Hoowa!",
            contextMenu);    
//
// Help for creating context menu
// Declaration
   private ContextMenu contextMenu = new ContextMenu();
// Initialization
   contextMenu.MenuItems.Add(new MenuItem("&Hide"));
   contextMenu.MenuItems.Add(new MenuItem("&Show"));
   contextMenu.MenuItems.Add(new MenuItem("-"));
   contextMenu.MenuItems.Add(new MenuItem("E&xit"));

Constructor 5

C#
// Step IV for using SystemTrayNotifyIcon class in your project
// This is the first constructor, which takes two parameters
// (parameter 1) System.Windows.Forms.Form form (passing
// reference of main form)
// (parameter 2) bool visible (pass true to show icon in System
// Tray else false)
// (parameter 3) string toolTip (pass a string to be set as tooltip
// for System Tray Icon)
// (parameter 4) Icon icon (pass an icon to be set in System Tray)
// (parameter 5) ContextMenu contextMenu (pass a ContextMenu
// System Tray Notifications)
   m_SysTrayNotify = new SystemTrayNotification.SystemTrayNotifyIcon(
     this, true, "Hoowa!,
     new System.Drawing.Icon("..\\..\\Default Icon\\PakFlag.ico")",
         contextMenu);    
//

Note: At least, you will have to provide two parameters for a constructor. Even in this case the program will work fine as it will be with default values, which are given below.

  • string toolTip : Application Name by default.
  • Icon icon : Application Icon by default.
  • ContextMenu contextMenu : Menu provided by SystemTrayNotifyIcon class by default.

Step V (optional)

This step is very interesting and useful but I am keeping it optional for beginners who are still afraid of using events and delegates in their program though using events in C# is pretty easy. Declare an event handler for SystemTrayNotificationEventArgs in
your main form class and attach it with SystemTrayNotifyIcon.OnStatusChanged event right after initialing SystemTrayNotifyIcon variable in your main forms constructor. The code is given below.

C#
// Step V for using SystemTrayNotifyIcon class in your project
// Add this function any where in your main form class to 
// catch System Tray Notifications
protected void SystemTrayNotificationHandler(object sender, 
    SystemTrayNotificationEventArgs e)
{
  switch (e.State)
  {
    case SystemTrayNotification.SystemTrayNotificationEventType.Hiding:
          break;
    case SystemTrayNotification.SystemTrayNotificationEventType.Showing:
          break;
    case 
    SystemTrayNotification.SystemTrayNotificationEventType.StartingAnimation:
          break;
    case 
     SystemTrayNotification.SystemTrayNotificationEventType.StopingAnimation:
          break;
    case SystemTrayNotification.SystemTrayNotificationEventType.IconChanged:
          break;
    case SystemTrayNotification.SystemTrayNotificationEventType.Disposing:
          break;
    default:      
          break;
  }
}
// Now attach this above function with 
// SystemTrayNotifyIcon.OnStatusChanged event right 
// after the initialization of SystemTrayNotifyIcon variable. 
// Add the following code.
   m_SysTrayNotify.OnStatusChanged += 
      new SystemTrayNotifyIcon.StatusChanged(SystemTrayNotificationHandler);
//

Step VI (optional - Making SystemTrayNotifyIcon to animate)

This step is quite easy and provides an extra functionality. If you want to animate SytemTrayNotifyIcon then you will have to provide series of icons which will be loaded and the shown in the form of animation. For animation at least two icons are required. I am using eight icons in my demo program. You can load these icons at any point in your program. Note that these icons are for different purpose so these are not mixed with the default icon given in the SystemTrayNotifyIcon constructor. Here is the code example of loading icon array.

C#
// Step VI for using SystemTrayNotifyIcon class in your project
// Here I am giving some helping code not related to 
// SystemTrayNotifyIcon class
// The extra code shows process of laoding icons in an icon array from files 
// Declaration of iconArray
   private System.Drawing.Icon [] iconArray;
// after the initialization of SystemTrayNotifyIcon variable.
// Add the following code.
   iconArray = new Icon[8];
   for (int i = 1; i <= iconArray.Length; i++)
   {
      try
      {
    iconArray[i-1] = new Icon("..\\..\\Animation Icons\\icon" + i +".ico");
      }
      catch (Exception e)
      {
    MessageBox.Show(e.Message, "Error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
   }
   // Actual code
   m_SysTrayNotify.LoadIcons(iconArray); 

   // Now to animate just call any one of the two overloaded 
   // Animate functions

   // It will animate five times now but INFINITELY if -1 is passed
   m_SysTrayNotify.Animate(5); 
                        OR
   // Actual code (1000 = 1 sec: Rate of change of icons during animation)
   m_SysTrayNotify.Animate(5, 1000); 

Step VII (Must - Disposing SystemTrayNotifyIcon)

This step is very important and if missed it might result in an exception. All you have to do is to just call

SystemTrayNotifyIcon 
Dispose() method in the first line of your main forms Dispose() method.

C#
// Step VII for using SystemTrayNotifyIcon class in your project
// Concentrate on the highlighted code
   protected override void Dispose( bool disposing )
   {
      m_SysTrayNotify.Dispose();    
      if( disposing )
      {
    if (components != null) 
    {
       components.Dispose();
    }
      }
      base.Dispose( disposing );
   }
// 

Stopping Animation: The animation which has been started by calling Animate() method can be stopped at once if the KeepAnimationAlive property of 

SystemTrayNotifyIcon 
class is set false. Once the Animate() method has been called,  you can start and stop animation with the values set by Animate() method just by makeing
KeepAnimationAlive 
property true and false.

C#
// Stopping animation using KeepAnimationAlive property of
SystemTrayNotifyIcon class
// here is the code
   m_SysTrayNotify.KeepAnimationAlive = false;
// 

Hiding and Showing NotifyIcon: For this case the

Visibility 
property of SystemTrayNotifyIcon class is used. Make it true and the icon will appear in System Tray, make it false and the icon will vanish from System Tray. Easy isn't it?

C#
// Hiding NotifyIcon using Visibility property of SystemTrayNotifyIcon class
// here is the code
   m_SysTrayNotify.Visibility = false;
// 

Conclusion

Though providing a System Tray Notification functionality is not a difficult task in C# but I think this class will help some new comers to C# in knowing the basics of Timers, Events, delegates to some extent and last but not the least, implementing System Tray Notification in their applications.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Pakistan Pakistan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralExcellent Pin
amirali25-Dec-07 21:45
amirali25-Dec-07 21:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.