用VISUALBASIC编写托盘程序
编写托盘程序主要解决两个问题:(1)创建、修改、删除托盘;(2)如何对托盘接收到的消息进行处理。这就要用到几个Windows API函数。
首先,Shell_NotifyIcon是用于托盘的Shell API。该API用到一个NOTIFYICONDATA结构.
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
其次,应该考虑怎样在VB中接收、处理托盘的消息(双击、单击、左键、右键)。C++、Delphi等语言对消息循环的处理较简单,但在VB中处理消息循环时必须应用Win32的SetWindowLong、CallWindowProc这两个API函数。SetWindowLong 函数利用GWL_WNDPROC 索引来创建窗口类的子类(窗口类是用来创建窗口的),它使用AddressOf关键字和回调函数(WindowProc)来截取消息并根据消息来执行相应的功能,如窗口的最大化、最小化、隐藏、退出等。CallWindowProc函数调用原窗口类缺省的指针,程序最后退出时可通过SetWindowLong来关闭子类,重新使原来的Windows过程成为回调函数。
本程序项目包括一个模块和一个窗体
1、模块源代码为:
Option Explicit ''强制定义每个使用的变量
Type NOTIFYICONDATA ''定义结构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
''以下为 Shell_NotifyIcon将用到的常量
Public Const NIF_ICON = &H2
Public Const NIF_MESSAGE = &H1
Public Const NIF_TIP = &H4
Public Const NIM_ADD = &H0
Public Const NIM_DELETE = &H2
Public Const NIM_MODIFY = &H1
''Shell_NotifyIcon的函数声明
Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA"
(ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long
''处理消息将用到的结构、常量、API声明
Type POINTAPI
x As Long
y As Long
End Type
Type Msg
hwnd As Long
message As Long
wParam As Long
lParam As Long
time As Long
pt As POINTAPI
End Type
Public Const WM_USER = &H400
Public Const WM_RBUTTONDOWN = &H204
Public Const WM_LBUTTONDBLCLK = &H203
Public Const GWL_WNDPROC = -4
Public trayflag As Boolean ''定义托盘图标是否在桌面上
Global lpPrevWndProc As Long
Global gHW As Long
Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
''以下过程为消息循环处理
Function WindowProc(ByVal hw As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
If hw = Form1.hwnd And uMsg = WM_USER+100 Then''检测到鼠标点动托盘图标
Select Case lParam
Case WM_RBUTTONDOWN ''鼠标右键按下
Form1.PopupMenu
Tags:
作者:佚名评论内容只代表网友观点,与本站立场无关!
评论摘要(共 0 条,得分 0 分,平均 0 分)
查看完整评论