Visual Basic.NET by Nitin Chopra
System Tray Icon
and Context Menus
First
of all we need to create some variables whose values we will assign
to the public properties to the object of this class.
Dim
ctxtMenu As System.Windows.Forms.ContextMenu
Dim
WithEvents menuItem1 As
System.Windows.Forms.menuItem
Dim
WithEvents nIcon As
System.Windows.Forms.NotifyIcon
Note
that we have declared these variables using WithEvents specifier
because we want to trap events corresponding to these objects. For
the icon we want to trap Click, DoubleClick events and for menuItems
Click event would do.
Now
we will initialize these variables in the constructor
'Add any initialization after the InitializeComponent() call
Me.components
= New System.componentModel.Container
Me.ctxtMenu
= New System.Windows.Forms.ContextMenu
Me.menuItem1
= New System.Windows.Forms.MenuItem
Now
initialize the contextmenu.
'init context menu
ctxtMenu.MenuItems.AddRange(New
System.Windows.Forms.MenuItem(){menuItem1})
Here AddRange
method takes an array of objects of type System.Windows.Forms.MenuItem.
above we have created a new array of this type and initialized it
with our menuItem object menuItem1 (we have only one menuItem till
now, to specify more menuItems we will give comma separated values).
Now
we will set the index of the menuItem and text to be shown
'set properties for menu items
menuItem1.Index = 0
menuItem1.Text = "Exit"
Now
we will actually create the icon.
'create notify icon
Me.nIcon
= New
System.Windows.Forms.NotifyIcon(Me.components)
System.Windows.Forms.NotifyIcon()
takes a parameter – a container which implements the System.componentModel.IContainer
interface. In .NET each form class already implements IContainer
interface. Private components
As System.ComponentModel.IContainer That
is why we pass
Me.components as
the parameter here.
|