当前位置: 开源爱好者 » 编程教程 » VB教程 » 正文

在任务栏添加图标的代码示例

VB添加托盘图标,在Windows托盘处显示一个程序图标,并添加右键菜单,通过这个小图标可弹出主窗口之类的,具体代码如下:

Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'声明Shell_NotifyIcon函数
Private Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" _
    (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long
 Const MAXS As Integer = 64
 Const NIF_ICON = &H2           '删除图标
 Const NIF_MESSAGE = &H1
 Const NIF_TIP = &H4
 Const NIM_ADD = &H0             '添加图标到任务栏
 Const NIM_DELETE = &H2
 Const WM_MOUSEMOVE = &H200
 Const WM_LBUTTONUP = &H202      '鼠标的左按钮单击
 Const WM_RBUTTONUP = &H205      '鼠标的右按钮单击
 Private Type NOTIFYICONDATA     '自定义结构
    cbSize           As Long
    hwnd             As Long
    uID              As Long
    uFlags           As Long
    uCallbackMessage As Long
    hIcon            As Long
    szTip            As String * MAXS
End Type
Private ICD As NOTIFYICONDATA
Private Sub Form_Load()
    ICD.hwnd = Me.hwnd    ' 获得句柄
    ICD.uID = Me.Icon     '任务栏上的图标
    ICD.uFlags = NIF_ICON Or NIF_MESSAGE Or NIF_TIP '设置有效性
    ICD.uCallbackMessage = WM_MOUSEMOVE      '鼠标事件
    ICD.hIcon = Me.Icon.Handle
    ICD.szTip = "本程序已放在任务栏" & vbNullChar '鼠标指向任务栏时的提示语言
    ICD.cbSize = Len(ICD)
    Call Shell_NotifyIcon(NIM_ADD, ICD)   '调用函数
    Me.Visible = False    '隐藏窗体
End Sub
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
    Dim MO As Single
    MO = X / Screen.TwipsPerPixelX   '判断鼠标动作
    If MO = WM_RBUTTONUP Or MO = WM_LBUTTONUP Then   '如果用户单击了左键或右键
       Me.PopupMenu ss    '则弹出菜单
    End If
End Sub
Private Sub move_Click() '删除任务栏中的图标
    Call Shell_NotifyIcon(NIM_DELETE, ICD)
End Sub
Private Sub show_Click()
    Me.Visible = True   '显示出窗体
End Sub
Private Sub exit_Click()  '退出
    Unload Me   '卸载窗体
End Sub

 

CopyRight 2018© 开源爱好者 All Rights Reserved 豫ICP备16030607号 隐私声明 网站地图