Click here to Skip to main content
11,478,174 members (74,391 online)
Click here to Skip to main content

Adding tray icons and context menus

, 10 Apr 2002 472.8K 1 170
Rate this:
Please Sign up or sign in to vote.
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.

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.

Adding the NotifyIcon member to your form

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

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.

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.

private ContextMenu m_menu;  

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

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.

m_notifyicon.ContextMenu = m_menu;

Now let's fill up those event handlers.

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.

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

Full Source Listing

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

Share

About the Author

Nish Nishant

United States United States
Nish Nishant is a Software Architect/Consultant based out of Columbus, Ohio. He has over 15 years of software industry experience in various roles including Lead Software Architect, Principal Software Engineer, and Product Manager. Nish is a recipient of the annual Microsoft Visual C++ MVP Award since 2002 (13 consecutive awards as of 2014).

Nish is an industry acknowledged expert in the Microsoft technology stack. He authored
C++/CLI in Action for Manning Publications in 2005, and had previously 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 vastly experienced in team management, mentoring teams, and directing all stages of software development.

Contact Nish : You can reach Nish on his google email id voidnish.

Website and Blog

Comments and Discussions

 
GeneralWrong Icon Pin
Erald Kulk23-Jun-03 0:11
sussErald Kulk23-Jun-03 0:11 
AnswerRe: Wrong Icon Pin
Richard Poole8-Nov-05 3:33
memberRichard Poole8-Nov-05 3:33 
GeneralHide the form window on startup Pin
Bryan Mau1-Dec-02 3:26
memberBryan Mau1-Dec-02 3:26 
GeneralRe: Hide the form window on startup Pin
Richard Birkby13-Dec-02 8:17
memberRichard Birkby13-Dec-02 8:17 
GeneralRe: Hide the form window on startup Pin
Pooran Prasad R.20-Jan-03 7:42
memberPooran Prasad R.20-Jan-03 7:42 
GeneralRe: Hide the form window on startup Pin
Richard Funke11-Dec-03 6:14
memberRichard Funke11-Dec-03 6:14 
GeneralRe: Hide the form window on startup Pin
BlueMerlyn23-Mar-04 1:34
memberBlueMerlyn23-Mar-04 1:34 
GeneralRe: Hide the form window on startup Pin
Anonymous3-Apr-04 4:09
sussAnonymous3-Apr-04 4:09 
GeneralRe: Hide the form window on startup Pin
TyronX9-Oct-04 9:52
sussTyronX9-Oct-04 9:52 
GeneralRe: Hide the form window on startup Pin
Anonymous9-Mar-05 20:44
sussAnonymous9-Mar-05 20:44 
GeneralRe: Hide the form window on startup Pin
KellyLlloyd5-Apr-05 8:30
memberKellyLlloyd5-Apr-05 8:30 
GeneralHelp !!! Pin
Noobish12-Oct-02 21:33
sussNoobish12-Oct-02 21:33 
GeneralRe: Help !!! Pin
soderstrom26-Nov-02 18:07
membersoderstrom26-Nov-02 18:07 
QuestionHuh ??? Pin
Christian Graus25-Aug-02 13:09
memberChristian Graus25-Aug-02 13:09 
Christian Graus was complaining that it was too easy and that the abominable allowance of gotos annoyed him.

That's a hell of a misquote, Nish. The forced use of goto is what annoys me ( in switch statements ), I have never complained that anything is too easy. I may have said that making it easy to write a form app might cause some people to make the mistake of thinking they were programmers, and release really bad apps to market because they look nice, but VB has been doing that for some time.....

Don't worry, I'm not furious, just want to set the record straight.... Smile | :)


Christian

We're just observing the seasonal migration from VB to VC. Most of these birds will be killed by predators or will die of hunger. Only the best will survive - Tomasz Sowinski 29-07-2002 ( on the number of newbie posters in the VC forum )

Cats, and most other animals apart from mad cows can write fully functional vb code. - Simon Walton - 6-Aug-2002

AnswerRe: Huh ??? Pin
Nishant S27-Aug-02 1:05
editorNishant S27-Aug-02 1:05 
GeneralRe: Huh ??? Pin
Christian Graus27-Aug-02 2:19
memberChristian Graus27-Aug-02 2:19 
QuestionHow to hide the windows when the minimize button has been pressed? Pin
Anonymous12-Jul-02 18:52
sussAnonymous12-Jul-02 18:52 
AnswerRe: How to hide the windows when the minimize button has been pressed? Pin
Nishant S12-Jul-02 19:04
subeditorNishant S12-Jul-02 19:04 
AnswerRe: How to hide the windows when the minimize button has been pressed? Pin
Joël3-Dec-02 12:43
sussJoël3-Dec-02 12:43 
AnswerRe: How to hide the windows when the minimize button has been pressed? Pin
venun16-Jan-05 20:01
membervenun16-Jan-05 20:01 
GeneralIt doesn't work in .NET Framework SDK Pin
Anonymous12-Jul-02 1:14
sussAnonymous12-Jul-02 1:14 
GeneralRe: It doesn't work in .NET Framework SDK Pin
Anonymous12-Jul-02 18:45
sussAnonymous12-Jul-02 18:45 
GeneralRe: It doesn't work in .NET Framework SDK Pin
Nishant S12-Jul-02 18:49
subeditorNishant S12-Jul-02 18:49 
GeneralRe: It doesn't work in .NET Framework SDK Pin
James T. Johnson12-Jul-02 19:41
editorJames T. Johnson12-Jul-02 19:41 
GeneralRe: It doesn't work in .NET Framework SDK Pin
Nishant S13-Jul-02 0:35
subeditorNishant S13-Jul-02 0:35 
GeneralRe: It doesn't work in .NET Framework SDK Pin
Anthony_Yio10-Mar-04 22:36
memberAnthony_Yio10-Mar-04 22:36 
GeneralOne little question Pin
sasdav2-Jul-02 3:52
membersasdav2-Jul-02 3:52 
GeneralRe: One little question Pin
Mike Thompson in the ATL, GA1-Nov-02 13:53
memberMike Thompson in the ATL, GA1-Nov-02 13:53 
GeneralRe: One little question Pin
Justin Armstrong7-Nov-02 8:43
memberJustin Armstrong7-Nov-02 8:43 
QuestionHow About to changes the try icon dynamically Pin
eponk17-Jun-02 8:30
membereponk17-Jun-02 8:30 
AnswerRe: How About to changes the try icon dynamically Pin
Nishant S18-Jun-02 19:26
memberNishant S18-Jun-02 19:26 
GeneralDoesn't work Pin
Anonymous14-Jun-02 1:40
memberAnonymous14-Jun-02 1:40 
GeneralRe: Doesn't work Pin
Nish - Native CPian14-Jun-02 1:44
memberNish - Native CPian14-Jun-02 1:44 
GeneralRe: Doesn't work Pin
Anonymous14-Jun-02 1:53
memberAnonymous14-Jun-02 1:53 
GeneralRe: Doesn't work Pin
Nathan Blomquist27-Jun-02 3:40
memberNathan Blomquist27-Jun-02 3:40 
GeneralSolution Pin
Ernesto Perales Soto12-Jul-03 6:10
memberErnesto Perales Soto12-Jul-03 6:10 
GeneralRe: Solution Pin
Jubjub22-Feb-07 12:28
memberJubjub22-Feb-07 12:28 
GeneralLaunch on start up. Pin
Cypher2-Jun-02 7:19
memberCypher2-Jun-02 7:19 
GeneralRe: Launch on start up. Pin
Nish - Native CPian12-Jun-02 15:56
memberNish - Native CPian12-Jun-02 15:56 
GeneralRe: Launch on start up. Pin
Richard Birkby13-Dec-02 8:23
memberRichard Birkby13-Dec-02 8:23 
GeneralGood! Pin
Alexandr Khilov28-May-02 12:58
memberAlexandr Khilov28-May-02 12:58 
GeneralRe: Good! Pin
Nish - Native CPian28-May-02 15:38
memberNish - Native CPian28-May-02 15:38 
GeneralNotify Icon Limitations Pin
Joel Matthias11-Apr-02 8:08
memberJoel Matthias11-Apr-02 8:08 
GeneralRe: Notify Icon Limitations Pin
Nish [BusterBoy]11-Apr-02 8:43
memberNish [BusterBoy]11-Apr-02 8:43 
GeneralRe: Notify Icon Limitations Pin
Joel Matthias11-Apr-02 8:57
memberJoel Matthias11-Apr-02 8:57 
GeneralRe: Notify Icon Limitations Pin
Nish [BusterBoy]11-Apr-02 9:03
memberNish [BusterBoy]11-Apr-02 9:03 
GeneralCleaning Up The Icon Pin
Joel Matthias11-Apr-02 8:04
memberJoel Matthias11-Apr-02 8:04 
GeneralRe: Cleaning Up The Icon Pin
Joel Matthias11-Apr-02 8:14
memberJoel Matthias11-Apr-02 8:14 
GeneralRe: Cleaning Up The Icon Pin
Nish [BusterBoy]11-Apr-02 8:38
memberNish [BusterBoy]11-Apr-02 8:38 
GeneralRe: Cleaning Up The Icon Pin
Nish [BusterBoy]11-Apr-02 8:37
memberNish [BusterBoy]11-Apr-02 8:37 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 11 Apr 2002
Article Copyright 2002 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid