This example shows you how to add an icon to the system tray, like many other utilities (ie a Virus Scanner).
First, add two Image Controls to your form, named imgOne, and imgTwo, and set their Picture properties to two different icons sized 16x16 (You can find some icons at %VBInstallPathCommonGraphics). Next, add a PictureBox called picHook. Finally, you need to add a menu item called mnuPopup, with two sub menu items called mnuPopupAbout and mnuPopupExit. Then, add the code below to the form.
Private 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
Private Const NIM_ADD = &H0
Private Const NIM_MODIFY = &H1
Private Const NIM_DELETE = &H2
Private Const WM_MOUSEMOVE = &H200
Private Const NIF_MESSAGE = &H1
Private Const NIF_ICON = &H2
Private Const NIF_TIP = &H4
Private Const WM_LBUTTONDBLCLK = &H203
Private Const WM_LBUTTONDOWN = &H201
Private Const WM_LBUTTONUP = &H202
Private Const WM_RBUTTONDBLCLK = &H206
Private Const WM_RBUTTONDOWN = &H204
Private Const WM_RBUTTONUP = &H205
Private Declare Function Shell_NotifyIcon Lib "shell32" Alias
"Shell_NotifyIconA" (ByVal dwMessage As Long, pnid As NOTIFYICONDATA)
As Boolean
Dim T As NOTIFYICONDATA
Private Sub Form_Load()
'Setup initial Tray Icon
T.cbSize = Len(T)
T.hWnd = pichook.hWnd
T.uId = 1&
T.uFlags = NIF_ICON Or NIF_TIP Or NIF_MESSAGE
T.ucallbackMessage = WM_MOUSEMOVE
T.hIcon = imgOne.Picture
T.szTip = "Recent" & Chr$(0)
Shell_NotifyIcon NIM_ADD, T
'Hide this form
Me.Hide
End Sub
Private Sub Form_Unload(Cancel As Integer)
'Unload this form. Important: always end with "unload
me".
T.cbSize = Len(T)
T.hWnd = pichook.hWnd
T.uId = 1&
Shell_NotifyIcon NIM_DELETE, T
End
End Sub
Private Sub mnuPopupAbout_Click()
MsgBox "Popup Example", , "About..."
End Sub
Private Sub mnuPopUpExit_Click()
Unload Me
End Sub
Private Sub pichook_MouseMove(Button As Integer, Shift As Integer, X As Single,
Y As Single)
Static State As Boolean
Static Popped As Boolean
Static Msg As Long
Msg = X / Screen.TwipsPerPixelX
If Popped = False Then
'As we don't want any popups during
the processing,
'turn off the MouseMove event by
setting popped=true
Popped = True
'Se the general section on how to
interpret Msg
Select Case Msg
Case
WM_LBUTTONDBLCLK
mnuPopupAbout_Click
Case
WM_LBUTTONDOWN
'In this case we have a twostate button, On or Off.
State = Not State
If State Then
'Set picture
T.hIcon = imgTwo.Picture
'Set tooltip
T.szTip = "Off" + Chr$(0)
Else
T.hIcon = imgOne.Picture
T.szTip = "On" + Chr$(0)
End If
Shell_NotifyIcon NIM_MODIFY, T
Case
WM_LBUTTONUP
Case
WM_RBUTTONDBLCLK
Case
WM_RBUTTONDOWN
Case
WM_RBUTTONUP
PopupMenu mnuPopup, 2, , , mnuPopupAbout
End Select
'OK to popup again
Popped = False
End If
End Sub
Comments