Click here to Skip to main content
11,637,662 members (76,975 online)
Click here to Skip to main content

Adding tray icons and context menus

, 10 Apr 2002 477.9K 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

You may also be interested in...

Comments and Discussions

 
AnswerRe: Windows Mobile Tray Icon Pin
Ajatashatru4-Aug-06 1:44
memberAjatashatru4-Aug-06 1:44 
QuestionWhat about the Compact Framework Pin
ddas7710-Nov-05 2:11
memberddas7710-Nov-05 2:11 
AnswerRe: What about the Compact Framework Pin
lisagitel2-Aug-07 10:08
memberlisagitel2-Aug-07 10:08 
Since you're using the NotifyIcon class from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetcomp/html/messagewindow.asp, just add the following to your application (to your Form class).

Create a context menu, add some menu items to it, add some click event handlers for the menu items.

Add these declarations:

[DllImport("coredll.dll")]
internal static extern IntPtr LoadIcon(IntPtr hInst, string IconName);

[DllImport("coredll.dll")]
internal static extern IntPtr GetModuleHandle(String lpModuleName);

private NotifyIcon notifyIcon;

Set up your notifyicon (probably in the constructor for your Form class):

notifyIcon = new NotifyIcon();
notifyIcon.Click += new EventHandler(notifyIcon_Click);
AddIcon();

Add these methods:

private void AddIcon()
{
IntPtr hIcon = LoadIcon(GetModuleHandle(null), "#32512");
notifyIcon.Add(hIcon);
}

private void RemoveIcon()
{
notifyIcon.Remove();
}

private void notifyIcon_Click(object sender, EventArgs e)
{
contextMenu1.Show(this, new System.Drawing.Point(20, 20));
}

private void Form1_Closing(object sender, CancelEventArgs e)
{
RemoveIcon();
}

QuestionYou have any idea how to manipulate/access clock in status area Pin
illegalguy7-Nov-05 13:27
memberillegalguy7-Nov-05 13:27 
GeneralNice, Nish Pin
Jon Sagara16-Aug-05 18:34
memberJon Sagara16-Aug-05 18:34 
GeneralUrgent Help Needed :context menu does not appear Pin
Gul Hunerkar13-Jul-05 1:42
memberGul Hunerkar13-Jul-05 1:42 
Generalthanks Pin
Gul Hunerkar11-Jul-05 0:03
memberGul Hunerkar11-Jul-05 0:03 
GeneralDesktop switch Pin
prof.hell24-Jun-05 12:21
memberprof.hell24-Jun-05 12:21 
QuestionHow to detect double clicking on Notification Icon Pin
Braulio Díez15-Apr-05 10:59
memberBraulio Díez15-Apr-05 10:59 
AnswerRe: How to detect double clicking on Notification Icon Pin
Braulio Díez15-Apr-05 11:24
memberBraulio Díez15-Apr-05 11:24 
GeneralShowing a balloon from the tray in C# Pin
BlueGuru23-Sep-04 11:10
memberBlueGuru23-Sep-04 11:10 
GeneralNice... Pin
Bassam Abdul-Baki14-Jun-04 6:09
memberBassam Abdul-Baki14-Jun-04 6:09 
GeneralYour Article. Pin
eggie521-Feb-04 13:16
membereggie521-Feb-04 13:16 
GeneralDoing the same for a Console Application Pin
mattdruid29-Feb-04 10:45
membermattdruid29-Feb-04 10:45 
GeneralRe: Doing the same for a Console Application Pin
Sufian Mehmood Sheikh18-Jul-05 23:43
memberSufian Mehmood Sheikh18-Jul-05 23:43 
GeneralOwnerDraw and NotifyIcon Pin
DalePres23-Jan-04 14:30
memberDalePres23-Jan-04 14:30 
Questionvb? Pin
coolerbob24-Nov-03 4:39
membercoolerbob24-Nov-03 4:39 
Generaldisable tray menu item Pin
martinbe22-Nov-03 14:16
membermartinbe22-Nov-03 14:16 
GeneralGhost icon remains in tray upon Exit(), when this.Visible set to false Pin
oblius27-Sep-03 21:33
memberoblius27-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
memberPeter 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
sussDotnetjunky30-Jun-04 20:13 
GeneralExtends possibilities of NotifyIcon Pin
Jremaud6-Jul-03 22:06
memberJremaud6-Jul-03 22:06 
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
memberRichard Poole8-Nov-05 2:33 
GeneralHide the form window on startup Pin
Bryan Mau1-Dec-02 2:26
memberBryan Mau1-Dec-02 2:26 

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
Web04 | 2.8.150728.1 | Last Updated 11 Apr 2002
Article Copyright 2002 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid