Using the Windows 9x / Windows NT System Tray from Visual Basic:
1. The System Tray is the small indented region of your Task Bar, containing miniature icons.
2. Programs which require little interaction can free up space on the Task Bar by moving to the System Tray.
Here are the declarations for all the following examples. Paste them into a Module in the (General) (Declarations) section.
Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long
Type NOTIFYICONDATA
cbSize As Long
hwnd As Long
uID As Long
uFlags As Long
uCallbackMessage As Long
hIcon As Long
szTip As String * 64
End Type
Public stray As NOTIFYICONDATA
Public Const NIM_ADD = &H0
Public Const NIM_DELETE = &H2
Public Const NIM_MODIFY = &H1
Public Const NIF_MESSAGE = &H1
Public Const NIF_ICON = &H2
Public Const NIF_TIP = &H4
Public Const WM_MOUSEMOVE = &H200
1. Since the user can control your program from its icon in the System Tray you will probably not want them to start the program more than once.
Prevent this with the following code in your Main Sub, or the Open Event of your first form:If App.PrevInstance Then MsgBox App.EXEName & " is already running. Right-click the icon in the System Tray to control it" End End If
2. Create a form (call it frmSysTray) which will contain the information needed by your System Tray icon. Set its Visible property to False.
3. Press CTRL-E and create the menu (mnuSysTray) which will appear when your user clicks on the icon.
4. Add a picture Box (Picture1). Set its scalemode to 3-pixel, and its Picture property to the Icon which you want to appear in the tray.
5. Add the following code to your form:
Private Sub Form_Load()
stray.cbSize = Len(stray)
stray.hwnd = Picture1.hwnd
stray.uID = 1&
stray.uFlags = NIF_MESSAGE Or NIF_ICON Or NIF_TIP
stray.uCallbackMessage = WM_MOUSEMOVE
stray.hIcon = Picture1.Picture
stray.szTip = "My Systray Program" & Chr$(0)
Shell_NotifyIcon NIM_ADD, stray
End Sub
Private Sub Picture1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
If X = 516 Then ' right mouse button down
Me.PopupMenu Me.mnuSysTray
ElseIf X = 515 Then ' left dbl-click
mnuSysTrayDefault_Click
End If
End Sub
6. When the time comes to place your icon in the System Tray, just use:
Load frmSysTray
You will usually want to hide or unload all your other forms at the same time.
7. You can do whatever you like from your menu. When the users exits your program you should tidy up the System Tray by removing your icon:
Shell_NotifyIcon NIM_DELETE, stray
End