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

Adding tray icons and context menus

Rate me:
Please Sign up or sign in to vote.
4.76/5 (58 votes)
10 Apr 20023 min read 626.9K   171   114
Beginner's Tutorial on adding tray icons and setting context menus

Introduction

As MFC/SDK programmers move into .NET, what surprises them most is the fact that everything is now so much more easier then ever before. Christian Graus was complaining that it was too easy and that the abominable allowance of gotos annoyed him. He might have a point there, but making coding easy is not such a bad thing after all. It's funny when you think of all the effort Chris Maunder and others put into those MFC & SDK tray icon classes that are ever so popular with copy/paste programmers. I dedicate this article to Chris M and others involved in the brilliant tray icon class project over the last few years.

Adding  the icon to your project

Ctrl-Shift-A will bring up the Add-New-Item dialog box. Select Icon File from the list of available templates. If the list is too populated to your liking select Resources from the tree control on the left. This will bring up a smaller list on the right and it will be easier for you to select Icon File. Now click open. You'll end up with the VS.NET icon editor. You may now create your icon here or copy/paste an icon from elsewhere.

Image 1

Now right click on this icon from Solution Explorer. Take properties. And change the Build Action property to Embedded Resource. This will instruct the compiler to embed this icon along with your EXE file, thus saving you the annoyance of having to distribute the icon with your EXE.

Image 2

Adding the NotifyIcon member to your form

Okay. Now that we have our icon ready we need to add it to our form class.

C#
private NotifyIcon m_notifyicon;

Alright, so we have added a NotifyIcon member. Now let's initialize it and set some default properties. This should be done from the form object's constructor.

C#
m_notifyicon = new NotifyIcon();
m_notifyicon.Text = "Hello, what's cooking?"; 
m_notifyicon.Visible = true; 
m_notifyicon.Icon = new Icon(GetType(),"Icon1.ico"); //Thanks to Hasaki for this.

Alright, now compile and run your program. You'll see the icon in your tray. That was rather simple, huh? But usually people like to add a context menu to their tray icons. A tray icon simply sitting there is not very useful.

Adding a context menu to the tray icon

The first thing we need to do is to add a ContextMenu member to our form.

C#
private ContextMenu m_menu;  

Now we need to initialize it and add some menu items.

C#
m_menu = new ContextMenu(); 
m_menu.MenuItems.Add(0, 
    new MenuItem("Show",new System.EventHandler(Show_Click))); 
m_menu.MenuItems.Add(1, 
    new MenuItem("Hide",new System.EventHandler(Hide_Click))); 
m_menu.MenuItems.Add(2, 
    new MenuItem("Exit",new System.EventHandler(Exit_Click)));

We have added three menu items and have also associated click event handlers for each of those menu items. I could have created an array of MenuItem objects but that's not really needed here.

Now we need to associate this ContextMenu with our tray icon. So we do this.

C#
m_notifyicon.ContextMenu = m_menu;

Now let's fill up those event handlers.

C#
protected void Exit_Click(Object sender, System.EventArgs e) 
{
    Close();
}
protected void Hide_Click(Object sender, System.EventArgs e) 
{
    Hide();
}
protected void Show_Click(Object sender, System.EventArgs e) 
{
    Show();
}

Okay. Compile and run it. Now right clicking on the tray icon brings up the context menu. You can hide and show the form window using the two menu options. And the "Exit" option will exit the application.

A small problem

Now you'll notice a slight annoyance. The tray icon does not vanish when you exit the program. But when you move the mouse over the tray the icon vanishes. So, what do we do to avoid that? Again as with everything else with this whole .NET thing, it's as easy as 1,2,3. Override your form object's Dispose function and put the following lines of code into it.

C#
protected override void Dispose( bool disposing ) 
{ 
    if( disposing ) 
    { 
        this.m_notifyicon.Dispose(); //we dispose our tray icon here
    }
    base.Dispose( disposing );
}

Full Source Listing

C#
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;

namespace TrayTest
{
    public class Form1 : System.Windows.Forms.Form
    {
        private NotifyIcon m_notifyicon;    
        private ContextMenu m_menu;        

        public Form1()
        {
            Text = "TrayIcon test program";    
        
            m_menu = new ContextMenu();                                    
            m_menu.MenuItems.Add(0,
                new MenuItem("Show",new System.EventHandler(Show_Click)));
            m_menu.MenuItems.Add(1,
                new MenuItem("Hide",new System.EventHandler(Hide_Click)));
            m_menu.MenuItems.Add(2,
                new MenuItem("Exit",new System.EventHandler(Exit_Click)));

            m_notifyicon = new NotifyIcon();
            m_notifyicon.Text = "Right click for context menu";
            m_notifyicon.Visible = true;
            m_notifyicon.Icon = new Icon(GetType(),"Icon1.ico");
            m_notifyicon.ContextMenu = m_menu;            
            
        }
        
        protected void Exit_Click(Object sender, System.EventArgs e) 
        {
            Close();
        }
        protected void Hide_Click(Object sender, System.EventArgs e) 
        {
            Hide();
        }
        protected void Show_Click(Object sender, System.EventArgs e) 
        {
            Show();
        }
        
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                this.m_notifyicon.Dispose();
            }
            base.Dispose( disposing );
        }
        
        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }
        
    }
}

Conclusion

I would like to thank James Johnson for his valuable tips while I was struggling with embedding icons into my exe. Also a special thanks to Colin for keeping me cheered up with Bobs while I was burying myself in despair after my bad experiences with the new CD writer.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions

 
GeneralRe: Doing the same for a Console Application Pin
Sufian Mehmood Sheikh18-Jul-05 23:43
Sufian Mehmood Sheikh18-Jul-05 23:43 
GeneralOwnerDraw and NotifyIcon Pin
DalePres23-Jan-04 14:30
DalePres23-Jan-04 14:30 
Questionvb? Pin
coolerbob24-Nov-03 4:39
coolerbob24-Nov-03 4:39 
Generaldisable tray menu item Pin
martinbe22-Nov-03 14:16
martinbe22-Nov-03 14:16 
GeneralGhost icon remains in tray upon Exit(), when this.Visible set to false Pin
oblius27-Sep-03 21:33
oblius27-Sep-03 21:33 
GeneralRe: Ghost icon remains in tray upon Exit(), when this.Visible set to false Pin
Peter Greenall17-Feb-04 7:49
Peter Greenall17-Feb-04 7:49 
GeneralRe: Ghost icon remains in tray upon Exit(), when this.Visible set to false Pin
dotnetjunky30-Jun-04 20:13
dotnetjunky30-Jun-04 20:13 
GeneralExtends possibilities of NotifyIcon Pin
Jremaud6-Jul-03 22:06
Jremaud6-Jul-03 22:06 
Can you help me?

I'm adding a ContextMenu to my NotifyIcon, and this menu would open differents forms (application, configuration...)

The problem is that the winform open and close quickly without the time for me to do anything with...

[ I hope you understand my problem, I'm french, so my english is not so good Cry | :(( ]

Thanks in advance for your help Wink | ;)

I have posted this question on forum (with code)

http://www.developersdex.com/vb/message.asp?r=3167635&p=1120[^]

.:[ CNSX ]:. [ Carquefou - 44 - FRANCE ]
GeneralWrong Icon Pin
Erald Kulk22-Jun-03 23:11
sussErald Kulk22-Jun-03 23:11 
AnswerRe: Wrong Icon Pin
Richard Poole8-Nov-05 2:33
Richard Poole8-Nov-05 2:33 
GeneralHide the form window on startup Pin
1-Dec-02 2:26
suss1-Dec-02 2:26 
GeneralRe: Hide the form window on startup Pin
Richard Birkby13-Dec-02 7:17
Richard Birkby13-Dec-02 7:17 
GeneralRe: Hide the form window on startup Pin
Pooran Prasad R.20-Jan-03 6:42
Pooran Prasad R.20-Jan-03 6:42 
GeneralRe: Hide the form window on startup Pin
Member 75837711-Dec-03 5:14
Member 75837711-Dec-03 5:14 
GeneralRe: Hide the form window on startup Pin
BlueMerlyn23-Mar-04 0:34
BlueMerlyn23-Mar-04 0:34 
GeneralRe: Hide the form window on startup Pin
Anonymous3-Apr-04 3:09
Anonymous3-Apr-04 3:09 
GeneralRe: Hide the form window on startup Pin
TyronX9-Oct-04 8:52
TyronX9-Oct-04 8:52 
GeneralRe: Hide the form window on startup Pin
Anonymous9-Mar-05 19:44
Anonymous9-Mar-05 19:44 
GeneralRe: Hide the form window on startup Pin
KellyLlloyd5-Apr-05 7:30
KellyLlloyd5-Apr-05 7:30 
GeneralHelp !!! Pin
Noobish12-Oct-02 20:33
sussNoobish12-Oct-02 20:33 
GeneralRe: Help !!! Pin
soderstrom26-Nov-02 17:07
soderstrom26-Nov-02 17:07 
QuestionHuh ??? Pin
Christian Graus25-Aug-02 12:09
protectorChristian Graus25-Aug-02 12:09 
AnswerRe: Huh ??? Pin
Nish Nishant27-Aug-02 0:05
sitebuilderNish Nishant27-Aug-02 0:05 
GeneralRe: Huh ??? Pin
Christian Graus27-Aug-02 1:19
protectorChristian Graus27-Aug-02 1:19 
QuestionHow to hide the windows when the minimize button has been pressed? Pin
Anonymous12-Jul-02 17:52
Anonymous12-Jul-02 17:52 

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.