怎样判断发生Resize事件时窗口是最小化状态呢?VB里没有现成的做法,我们可以用非富的API函数。API函数库里有一个函数IsIconic(ByVal hwnd As Long),它就是专门判断窗口是否已最小化的。这样当Form产生Resize事件时,用IsIconic函数判断一下窗口是否为最小化状态,就可知道是否用户按了最小化按钮。
最关键的一步就是将图标显示在通知栏里,VB里没有现成的做法,我们还得用API函数。API函数库里有一个函数Shell_NotifyIcon(ByVal dwMessage As Long, lpData As NOTIFYICONDATA),是专门操作(包括添加、修改、删除)通知栏里图标的。
点一下通知栏图标,会出现一些诸如"退出"、"显示窗口"的弹出菜单,怎样实现弹出菜单呢?这个很容易实现,因为点击图标会触发图标所在窗口的MouseDown事件,我们把弹出菜单触发过程写入Form1_MouseDown事件即可。具体例程如下:
第一步、为了增强程序的可移植性,我们新建一个模块,取名为:NoticeIcon,在此模块中定义一些常量、自定义类型、所需的API函数说明及操作通知栏图标的三个自定义函数(添加、修改、删除),模块NoticeIcon具体代码如下所示:
Public Const DefaultIconIndex = 1 图标缺省索引
Public Const WM_LBUTTONDOWN = &H201 按鼠标左键
Public Const WM_RBUTTONDOWN = &H204 按鼠标右键
Public Const NIM_ADD = 0 添加图标
Public Const NIM_MODIFY = 1 修改图标
Public Const NIM_DELETE = 2 删除图标
Public Const NIF_MESSAGE = 1 message 有效
Public Const NIF_ICON = 2 图标操作(添加、修改、删除)有效
Public Const NIF_TIP = 4 ToolTip(提示)有效
API函数声明
图标操作
Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long
判断窗口是否最小化
Declare Function IsIconic Lib "user32" (ByVal hwnd As Long) As Long
设置窗口位置和状态(position)的功能
Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
定义类型
通知栏图标状态
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
函数定义
添加图标至通知栏
Public Function Icon_Add(iHwnd As Long, sTips As String, hIcon As Long, IconID As Long) As Long
参数说明:iHwnd:窗口句柄,sTips:当鼠标移到通知栏图标上时显示的提示内容
hIcon:图标句柄,IconID:图标Id号
Dim IconVa As NOTIFYICONDATA
With IconVa
.hwnd = iHwnd
.szTip = sTips + Chr$(0)
.hIcon = hIcon
.uID = IconID
.uCallbackMessage = WM_LBUTTONDOWN
.cbSize = Len(IconVa)
.uFlags = NIF_MESSAGE Or NIF_ICON Or NIF_TIP
Icon_Add = Shell_NotifyIcon(NIM_ADD, IconVa)
End With
End Function
删除通知栏图标(参数说明同Icon_Add)
Function Icon_Del(iHwnd As Long, lIndex As Long) As Long
Dim IconVa As NOTIFYICONDATA
Dim L As Long
With IconVa
.hwnd = iHwnd
.uID = lIndex
.cbSize = Len(IconVa)
End With
Icon_Del = Shell_NotifyIcon(NIM_DELETE, IconVa)
End Function
修改通知栏图标(参数说明同Icon_Add)
Public Function Icon_Modify(iHwnd As Long, sTips As String, hIcon As Long, IconID As Long) As Long
Dim IconVa As NOTIFYICONDATA
With IconVa
.hwnd = iHwnd
.szTip = sTips + Chr$(0)
.hIcon = hIcon
.uID = IconID
.uCallbackMessage = WM_LBUTTONDOWN
.cbSize = Len(IconVa)
.uFlags = NIF_MESSAGE Or NIF_ICON Or NIF_TIP
Icon_Modify = Shell_NotifyIcon(NIM_MODIFY, IconVa)
End With
End Function