8.7 Displaying System Tray Icons

 <  Day Day Up  >  

You want your application to display a system tray icon as another means to access its functionality.


Technique

The forms designer toolbox contains a NotifyIcon control that allows you to place an icon in the system tray in Windows, as shown in Figure 8.2. To associate a NotifyIcon with your Windows Form, drag a NotifyIcon control from the form designer toolbox and drop it on the form. In most instances, a NotifyIcon has an associated context menu. The procedure to create a ContextMenu object and associate it with the NotifyIcon is the same as shown in the previous recipe.

Figure 8.2. Use the NotifyIcon control to display a system tray icon for applications that run in the background.

graphics/08fig02.gif

Comments

If you want your application's main form to remain invisible when the application starts and only to show when the user selects a context menu item from the NotifyIcon , you have to perform a few additional steps in addition to setting the Visible property of your Windows Form. The generated code that was created when you initially created your application calls the Application.Run method, passing an instance of your form as the parameter of the method. Even if you set the Visible property of your form to false , the form still shows because the overloaded Application.Run method that accepts a Form object in turn sets the Visible property to true . Therefore, modify the application entry point method, Main , by creating an instance of your form before Application.Run is called, and then call Application.Run without any parameters, as shown in the following code:

 
 [STAThread] static void Main() {     Form1 mainForm = new Form1();     Application.Run(); } 

If you want to add the ability to exit your application using the context menu of the notify icon, you must explicitly remove the icon from the tray before exiting your application. If you do not, the tray icon remains in the tray even when your application has exited, and it does not disappear until the mouse hovers over it. Therefore, set the Visible property of your NotifyIcon property to false when your application exits.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net