ublic Const WM_USER = &H400
Public Const WM_LBUTTONUP = &H202
Public Const WM_MBUTTONUP = &H208
Public Const WM_RBUTTONUP = &H205
Public Const TRAY_CALLBACK = (WM_USER + 1001&)
Public Const GWL_WNDPROC = (-4)
Public Const GWL_USERDATA = (-21)
Public Const NIF_ICON = &H2
Public Const NIF_TIP = &H4
Public Const NIM_ADD = &H0
Public Const NIF_MESSAGE = &H1
Public Const NIM_MODIFY = &H1
Public Const NIM_DELETE = &H2
''记录 设置托盘图标的数据 的数据类型NOTIFYICONDATA
Public 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
''TheData变量记录设置托盘图标的数据
Private TheData As NOTIFYICONDATA
'' *********************************************
'' 新的窗口过程--主程序中采用SetWindowLong函数改变了窗口函数的地址,消息转向由NewWindowProc处理
'' *********************************************
Public Function NewWindowProc(ByVal HWnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
''如果用户点击了托盘中的图标,则进行判断是点击了左键还是右键
If Msg = TRAY_CALLBACK Then
''如果点击了左键
If lParam = WM_LBUTTONUP Then
''而这时窗体的状态是最小化时
If TheForm.WindowState = vbMinimized Then _
''恢复到最小化前的窗体状态
TheForm.WindowState = TheForm.LastState
TheForm.SetFocus
Exit Function
End If
End If
''如果点击了右键
If lParam = WM_RBUTTONUP Then
''则弹出右键菜单
TheForm.PopupMenu TheMenu
Exit Function
End If
End If
''如果是其他类型的消息则传递给原有默认的窗口函数
NewWindowProc = CallWindowProc(OldWindowProc, HWnd, Msg, wParam, lParam)
End Function
'' *********************************************
'' 把主窗体的图标(Form1.icon属性可改变)添加到托盘中
'' *********************************************
Public Sub AddToTray(frm As Form, mnu As Menu)
''保存当前窗体和菜单信息
Set TheForm = frm
Set TheMenu = mnu
''GWL_WNDPROC获得该窗口的窗口函数的地址
OldWindowProc = SetWindowLong(frm.HWnd, GWL_WNDPROC, AddressOf NewWindowProc)
''知识点滴:HWnd属性
''返回窗体或控件的句柄。语法: object.HWnd
''说明:Microsoft Windows 运行环境,通过给应用程序中的每个窗体和控件
''分配一个句柄(或 hWnd)来标识它们。hWnd 属性用于Windows API调用。
''将主窗体图标添加在托盘中
With TheData
.Uid = 0 ''忘了吗?参考一下前面内容,Uid图标的序号,做动画图标有用
.HWnd = frm.HWnd
.cbSize = Len(TheData)
.HIcon = frm.Icon.Handle
.UFlags = NIF_ICON ''指明要对图标进行设置
.UCallbackMessage = TRAY_CALLBACK
.UFlags = .UFlags Or NIF_MESSAGE ''指明要设置图标或返回信息给主窗体,此句不能省去
.cbSize = Len(TheData) ''为什么呢?我们需要在添加图标的同时,让其返回信息
End With ''给主窗体,Or的意思是同时进行设置和返回消息
Shell_NotifyIcon NIM_ADD, TheData ''根据前面定义NIM_ADD,设置为“添加模式”
End Sub
'' *********************************************
'' 删除系统托盘中的图标
'' *********************************************
Public Sub RemoveFromTray()
''删除托盘中的图标
With TheData
.UFlags = 0
End With
Shell_NotifyIcon NIM_DELETE, TheData ''根据前面定义NIM_DELETE,设置为“删除模式”
''恢复原有的设置
SetWindowLong TheForm.HWnd, GWL_WNDPROC, OldWi