Saturday, November 10, 2007

Placing Your C# Application in the System Tray

  1. To get started, open an existing C# Windows form (or create a new one).
  2. Open the Visual Studio Toolbox.
  3. Drag a NotifyIcon control onto the form. The control will named notifyIcon1 by default and placed below the form because it has no visual representation on the form itself.
  4. Set the NotifyIcon control's Text property to the name you want to appear when the user pauses the mouse over the application's icon. For example, this value could be "KillerApp 1.0".
  5. Set the control's Icon property to the icon that you want to appear in the System Tray
  6. Add an event handler for the form's Resize event that will hide the application when it's minimized. That way, it won't appear on the task bar.
  7. private void Form1_Resize(object sender, System.EventArgs e)
    {
      if (FormWindowState.Minimized == WindowState)
         Hide();
    }
    
  8. Add an event handler for the NotifyIcon.DoubleClick event and code it as follows so that the application will be restored when the icon is double-clicked.
  9. private void notifyIcon1_DoubleClick(object sender,
                                        System.EventArgs e)
    {
       Show();
       WindowState = FormWindowState.Normal;
    }
    

At this point, your application will fuction perfectly in terms of an icon appearing in the System Tray when the application is run (see Figure 1), the application not appearing on the task bar when minimized and the application restoring itself when the Tray icon is double-clicked.

Figure 1

Now, let's see the steps involved with adding a context menu to the icon.

  1. From the Visual Studio Toolbox, drag a ContextMenu control onto the form.
  2. Right-click the ContextMenu control and select the Edit Menu.option.
  3. Type in the options that you want to appear in your context menu. For example, you can add options such as Restore and Close Application.
  4. As with any menu, double-click the menu item to create and code each item's handler. As an example, you could copy the code from the form's DoubleClick handler into the context menu's Restore handler and for the Close Application menu item; simply call the form's Close method.
  5. Finally, set the NotifyIcon control's ContextMenu property to the new context menu you just created by selecting the menu from the drop-down list. Figure 2 shows a simple Tray context menu.

1 comment:

  1. Another example in german:
    http://www.ploetzeneder.eu/softwareentwicklung/cvbnet/44-programm-im-tray-verstecken.html

    ReplyDelete