SIGN UP MEMBER LOGIN:    
ARTICLE

Implementing System Tray Using C# Control

Posted by Sivaraman Dhamodaran Articles | Windows Controls C# January 22, 2012
In this article we will implement a system tray icon sample. The sample, when closed, sits in the system tray and continues doing its task.
Reader Level:
Download Files:
 

Introduction

 

The NotifyIcon control is useful for providing the system tray support for your application. This control is grouped under the common controls inside the developer studio's toolbox. Usually when the user minimizes the application, an icon in the system tray area appears. When you right click (Sometimes clicking also, depending on how you implement it) it displays a context menu and you can take action from there.

 

When will it be useful? Some applications run in background or some tasks of the application takes more time to complete or simply the interaction with the user is very less/read only (Take information application). These applications can use the system tray concept. Some examples are: Your Internet connection, TaskManager etc

 

About the Sample

 

The sample example screen shot is shown below:

 

Pic01.JPG

 

The example shown above will take input seconds in the textbox and when you click on the button Track Seconds elapsed, a counter next to the button shows the remaining seconds. When you click the close button, this example actually runs in the background and an icon will be placed in the system tray. Right-clicking the system tray Icon for this sample will pop-up a menu and you can actually exit the sample by clicking the exit menu item or you can come back and see a dialog by clicking the remaining seconds Menu item. This is shown below:

 

Pic02.JPG

 

So all we need to develop the above shown sample are listed below:

  1. An Icon that displays in the system tray. In the above screen shot it is marked in red.
  2. A Context menu that will display when the tray icon is right clicked.
  3. A timer that is useful to track the seconds entered.

When the sample is closed and the timer is still running, say 11 seconds remaining as shown above, the tray icon will notify you with a tool tip stating that the seconds you specified has expired. This is shown below:

 

Pic03.JPG

 

Let is start designing the form first, then move to the coding.

 

Build the Context Menu

 

The form design is simple. It has a label, textbox and a button explanation around that is not required. In the previous section we saw that a menu is displayed when we right-click over the icon in the system tray. So first we need to add the context menu to the form, then start adding the menu items to it. Setting up the context menu is shown in the following video.

 

Video 1: Link

 

Adding NotifyIcon Control

 

When the application's close button is clicked we are going to actually hide it and display the icon over the system tray area, which is usually at the lower right hand corner of the task bar. NotifyIcon is the control that will make this task easier. In our sample, after adding this control the following properties are set:

  • BallonTipText: This property will display the information text that needs to be appeared on the balloon tool tip. A tip that appears as a notification.
  • BallonTipTitle: Title given to the balloon tool tip.
  • BallonTipIcon: Icon for the tool tip that appears before the tool tip title.
  • ContextMenu: A context menu associated to this Tray Icon. We will just select the context menu created in the previous step as the value for this property.
  • Text: This text gets displayed when you move the mouse over the icon in the system tray.
  • Icon: This property takes the Icon as input and displays that on the system tray area.

The following is the video that shows how we set these properties for the NotifyIcon Control.

 

Video 2: Link

 

Add Timer component

 

Now the NotifyIcon control is set (Of course we should write some code) and ready to implement. Before that our form requires a way to communicate with the tray icon in the task bar when the number of seconds specified in the textbox has elapsed. We will use a timer for that and the timer procedure will run for every 1000 milliseconds (1 sec). Setting up the timer component to the form is shown in the following video. The interval property is set to 1000 milliseconds and it sets the control to raise the tick event for every 1-second.

 

Video 3: Link

 

Source Code: Some basic implementation

  1. First the variable required for the implementation is declared. The following are the declarations:

    //Tray_01: Variable to know when should I exit the form

    private bool EndNow = false;

    private int m_secs ;

     

    The Boolean variable EndNow tells when should we actually exit the form. The variable is used by the piece of code that runs when the close button (x) of the form is pressed. The variable m_secs will track the remaining time before raising the notification message.

  2. Next when the button Track Seconds Elapsed is clicked, we enable the timer and it will raise the Tick event for each second that passes. The Button click handler is shown below:

     

    //Tray_02: Simply wait for the Seconds to elapse

    private void btnMonitor_Click(object sender, EventArgs e)

    {

        m_secs = Int32.Parse(txtSeconds.Text);           

        timer.Enabled = true;

    }

     

    Well the Parse function converts the number entered into the textbox and stores that in the m_secs class level variable and it is going to crash the sample when you enter something other than a number. I do not want to divert it from placing the validation part of textbox.


  3. We know that the context menu has two menu items. The handler for those menu items are shown below:

     

    //Tray_03: Implement Context Menu

    private void mnuRemaining_Click(object sender, EventArgs e)

    {

        this.Show();

    }

    private void mnuExit_Click(object sender, EventArgs e)

    {

        EndNow = true;

        this.Close();

    }

     

    When we click the Remaining item, the show() method makes the form visible and the person can look at the form to know how much time remains. And when the exit button is clicked, we just set the EndNow variable to true and then make a call to Close() to close the form. This close function will raise an event before actually closing the form and the handler for that event (that will be shown; continue reading) will check this variable to know OOOk, now I can dismiss the form EndNow is set to true.

  4. When we load the form we just hide the TrayIcon by setting its Visible property to false. The code is shown below:

     

    //Tray_06: Set the Tray Icon visibility to False

    private void frmTrayIcon_Load(object sender, EventArgs e)

    {

        TrayIcon.Visible = false;

    }

Source Code: Displaying System Tray Icon

 

We know that the when the user clicks the x button to close the form, we should display the system tray icon in the task bar. Before closing the form .Net framework will raise a FormClosing event providing a chance for doing something like clearing activities like closing the resources, releasing the memory (Forceful not respecting G.collector) or even having chance to say "Hey don't close". That last one we are doing here by providing the handler for the event that we are discussing. The following is code for it:

 

//Tray_05: When the close button clicked, hide the form and show TrayIcon

private void frmTrayIcon_FormClosing(object sender, FormClosingEventArgs e)

{

    if (EndNow == false)

    {

        e.Cancel = true;

        Application.DoEvents();

        this.Hide();

        TrayIcon.Visible = true;

    }

}

 

In the above code first we are checking the variable to make sure we can close the form. When the variable is set to false (the form's load is already set it to false) the first thing we did was to cancel the close action. Setting the cancel property of the passed in FormClosingEventArgs to true does this. After requesting to cancel the close operation, we displayed the TrayIcon by setting the Visible property to true. And before this, we are hiding the form, as it has to be run in the background using the call to the Hide() method.

 

Source Code: Displaying Balloon Tooltip

 

The balloon tooltip will be displayed when the seconds entered in the input textbox has expired. All we need to do is, provide a handler for the Tick event of the timer, and when we it is time, ask the System tray icon to display the balloon text. The code for this event handler is shown below:

 

//Tray_04: Timer will display the remaining seconds and ends

//              when all the seconds passed by. Also it shows balloon tip

//              When you are in form hided state (Tray iconified)

private void timer_Tick(object sender, EventArgs e)

{

    m_secs = m_secs - 1;

    lblElapsed.Text = m_secs.ToString();

    if (m_secs == 0)

    {

        timer.Enabled = false;

        if (this.Visible == false)

            TrayIcon.ShowBalloonTip(5);

    }

}

 

In the above code (Runs for every 1 seconds until the timer is disabled) first we are decrementing the seconds. So the variable m_secs will actually hold the remaining time to raise the notification. When the seconds reads zero, we disable the timer (timer.Enabled = false) so that this procedure won't run again. Then the call to the ShowBalloonTip of the NotifyIcon object will display the tool tip for 5 seconds. The parameter says display it for five seconds.

 

Watch the following video to see the sample in action:

 

Video 4: Link

Login to add your contents and source code to this article
share this article :
post comment
 

If it takes time for you to stream the video, you can visit my latest blog and download the videos in compressed format and that takes very less time.

Posted by Sivaraman Dhamodaran Jan 24, 2012

Hi Sivaraman. Its a very useful article.

Posted by Maria Johnson Jan 23, 2012

It's a very well explanation about the system tray, and such a great effort to accomplish this so keep it up.....

Posted by Amit Maheshwari Jan 23, 2012

Here you have to nice implementation.

Posted by Arjun Panwar Jan 23, 2012
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Become a Sponsor