.Net framework provides classes and methods to manage our application at system tray easily.
In this article an trying to explain how we can place our application icon in system tray and how to capture the events.
Adding a notify icon
private System.Windows.Forms.NotifyIcon myAppIcon;
myAppIcon.Icon = new Icon(this.GetType(), "icon1.ico");
myAppIcon.Text = "My Application";
Adding a context menu
For adding context menu we can use the System.Windows.Forms.ContextMenu class.
For adding menu items to the contextmenu we can use System.Windows.Forms.MenuItem class.
private System.Windows.Forms.NotifyIcon myAppIcon;
private System.Windows.Forms.ContextMenu contextMenu;
this.contextMenu = new System.Windows.Forms.ContextMenu();
this.myAppIcon.ContextMenu = this.contextMenu;
this.myAppIcon.Icon = new Icon(this.GetType(), "icon1.ico");
this.myAppIcon.Text = "My Application";
this.myAppIcon.Visible = true;
this.myAppIcon.DoubleClick += new System.EventHandler(this.myAppIcon_DoubleClick);
this.contextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemSettings,
this.menuItemEnabled,
this.menuItemQuit});
this.menuItemSettings.Index = 0;
this.menuItemSettings.Text = "&Application Settings";
this.menuItemSettings.Click += new System.EventHandler(this.menuItemSettings_Click);
this.menuItemEnabled.Checked = true;
this.menuItemEnabled.Index = 1;
this.menuItemEnabled.Text = "&Enabled";
this.menuItemEnabled.Click += new System.EventHandler(this.menuItemEnabled_Click);
this.menuItemQuit.Index = 2;
this.menuItemQuit.Text = "&Exit";
this.menuItemQuit.Click += new System.EventHandler(this.menuItemQuit_Click);
There is another helpful class System.Management.ManagementEventWatcher which can handle the system tray icon contains two static methods start() stop() to enable and disable the system tray functionality.
private void StartMonitoring()
{
notifyIcon.Icon = new Icon( this.GetType() , "Enabled.ico" );
notifyIcon.Text = "PriorityMonitor (Enabled)";
if ( ProcessWatcher == null )
{
WqlEventQuery wmiQuery = new WqlEventQuery( "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA \"Win32_Process\"" );
ProcessWatcher = new ManagementEventWatcher( wmiQuery );
ProcessWatcher.EventArrived +=new EventArrivedEventHandler(ProcessWatcher_EventArrived);
}
ProcessWatcher.Start();
}
private void StopMonitoring()
{
notifyIcon.Icon = new Icon( this.GetType() , "Disabled.ico" );
notifyIcon.Text = "PriorityMonitor (Disabled)";
if ( ProcessWatcher == null ) return; // Stop not needed!
ProcessWatcher.Stop();
}
1 comment:
An example how to hide a programm in tray
Post a Comment