Monday, February 22, 2010

Displaying context menu for system tray icon in C#

In the last post, I talked about creating a system tray icon for applications. Often, there is also a need to show menus when the user clicks this icon. Let’s see how we can accomplish this.

To enable menus on the system tray icon, we need to use the ContextMenuStrip control. Drop this control from the toolbox onto the form design surface. The control will be displayed in the bottom half, below the actual form. We need to do 3 things now to make the menu work:

  • Link the menu to the icon – The ContextMenuStrip only represents a menu of options. To make it work, we need to link it to another control, in our case, it is the NotifyIcon control. Select the NotifyIcon control, go to its Properties and set the ContextMenuStrip property to point to the menu control.
  • Add the menu options – Select the menu control and go to its properties. For the Items property, click on the Ellipsis to open the Items Collection Editor. Here, we can add the menu items we want to appear in the context menu
  • Add event handlers for menu options – Finally, we need to specify what should happen when the menu items are clicked. For this, we need to attach event handlers. Attaching event handlers is pretty straightforward. In the code behind, use the normal <controlName>.<eventName> += <eventHandler> syntax to specify the event handler. For example, for a control named menuExit, we can attach menuExit_Click as a Click event handler using the following line:

menuExit.Click += new EventHandler(menuExit_Click);

You can add as many menu options as you want. In fact, it is quite common to have applications like download accelerators and anti virus software to run in the background with an icon in the system tray that has huge (often multi level) menus. But now, creating such menus is no longer limited to large product companies. You also know the trick for making menus like these :-)

1 comment: