VBNET:SystemTray
From GPWiki
The wiki is now hosted by GameDev.NET at wiki.gamedev.net. All gpwiki.org content has been moved to the new server. However, the GPWiki forums are still active! Come say hello. There are two ways to place an item in the system tray: using strictly code or placing a NotifyIcon control on a form. We'll look at both ways in this article. Using Code Start a new project and add a module. Add the following code to the module: Private systray As New NotifyIcon() Public Sub Main() Dim mnu As New ContextMenu() Dim mnuitem As New MenuItem() mnuitem.Text = "Exit" AddHandler mnuitem.Click, AddressOf EndApp mnu.MenuItems.Add(mnuitem) systray.ContextMenu = mnu systray.Icon = New Icon(Application.StartupPath & "\systray.ico") systray.Visible = True Application.Run() End Sub Private Sub EndApp(ByVal sender As Object, ByVal e As EventArgs) systray.Visible = False Application.Exit() End Sub Build the project. Place an icon file in the bin folder of the project and name it "systray.ico" (there are plenty of icons included with VB, check the folder: C:\Program Files\Microsoft Visual Studio .NET\Common7\Graphics, or wherever you installed). Make sure the startup object for the project is "Sub Main" and run the project. You'll see the icon in the system tray. Right click on it and you should get the Exit menu item. Click it and the application will end. One problem doing it this way is that you have to write all of the code for creating the menu items. If you have a lot of them it gets to be bothersome. If you're application has no interface, however, and you don't want to go through the trouble of creating a form just to hold the NotifyIcon object, it's about the only way to go. Normally your application will have at least one form and you can do it the easier way (for me anyway). The NotifyIcon Control Add a form to the project you previously created and find the NotifyIcon control on the Toolbar. Drop one on the form. Unlike previous versions of VB, it appears in a little area below the actual form. Click it and display the Properties dialog. Set the Icon property, drop a ContextMenu control on the form and add an Exit menuitem to it. Double Click on the Exit menuitem and add the following: NotifyIcon1.Visible = False Me.Close() Set the startup object for the project to Form1 and run the project. You'll get the same results in the system tray.
|


