VB托盘程序详解
VB.NET编写托盘程序
编写托盘程序
编写托盘程序
托盘程序作为一类特殊的窗体,其快捷图标显示在系统托盘中,窗体本身则隐藏不可见。
在.NET之前版本的VB中编写托盘程序是十分困难的,但是提供的新的NotifyIcon组件却使VB初学者也能轻松编写一个这样的程序:
新建“Windows应用程序”,设置主窗体Opacity属性为0,FormBorderStyle属性为None,ShowInTaskbar属性为False,这样窗体将在启动后隐藏。
在窗体上放置一个NotifyIcon组件NotifyIcon1,一个ContextMenu(弹出菜单)组件 ContextMenu1,并根据需要为ContextMenu1添加菜单项。
设置NotifyIcon1的ICON属性,这个图标就是应用程序出现在系统托盘中的快捷图标;设置NotifyIcon1的Text属性为“ 托盘程序”,这就是鼠标移动到托盘图标时弹出的文字说明;设置NotifyIcon1的ContextMenu属性为ContextMenu1,也就是右键单击快捷图标时的弹出菜单为 ContextMenu1。
OK,按F5运行!
几乎不用编写代码,一个托盘程序就这样轻松实现了。
VB教程
VB教程网/VBjc/Vb.HTM编写趣味撞球小游戏文章来源:沐风经典文章作者:佚名Visual Basic是一个功能强大的工具,它有一大特点就是易学易用,下面我们就通过写一个“趣味撞球”的程序来初步体会一下。
首先启动VB5,新建一个标准的EXE工程。
此时可以看到,工程包括一个Form1框体。
在Form1边框的右下角按住鼠标左键不放,拖动鼠标把Form1的面积改为适当大小,比如6930×4320。
再在属性框中把Form1的ScaleMode 属性改为3-Pixel,表明我们将以像素为我们的坐标计算单位,把Form1的StartUpPosition 属性设为2-CenterScreen,使运行时窗体出现在屏幕正中。
现在,在控件面板上选取CommandButton(命令按钮)控件,为Form1添加Command1和Command2两个按钮控件,把它们的大小设为121×25,再在属性框中把Command1的Caption填为“&GO”,把Command2的Caption填为“&QUIT”,并把Command1放到框体的右上角,把Command2放到框体的右下角。
然后,在控件面板上选取Timer(时钟)控件,为Form1添加一个Timer1时钟控件。
再在属性框中把它的Enabled属性改为False,Interval属性改为50,前一个值表示该时钟控件是否激活,后一个值决定该时钟控件产生Timer事件的间隔时间,我们将用它来控制小球的移动频率。
到此为止,我们已经完成了全部的界面设计工作。
接下来要做的全部工作就是填入程序代码了。
Dim BallX As IntegerDim BallY As IntegerDim AddX As IntegerDim AddY As IntegerDim HitX As IntegerDim W As IntegerDim H As IntegerPrivate Sub Command1_Click()BallX=Int(Rnd(1)*Form1.ScaleWidth/10)*5+25BallY=Int((Form1.ScaleHeight)/10)*5AddX=-5AddY=-5Form_PaintTimer1.Enabled=TrueEnd SubPrivate Sub Command2_Click()EndEnd SubPrivate Sub Form_MouseMove(Button As Integer,Shift As Integer,X As Single,Y As Single) X=X-50If X<15 Then X=15If X>W-105 Then X=W-105HitX=XIf Timer1.Enabled=True ThenLine(16,H-5)-(W-6,H),&HC0C0C0,BF Line(HitX,H)-(HitX+100,H-5),0,BF End IfEnd SubPrivate Sub Form_Paint()ClsW=Int((ScaleWidth-140)/5)*5H=Int((ScaleHeight-10)/5)*5 BackColor=&HC0C0C0Line(10,10)-(15,H),0,BFLine(W-5,10)-(W,H),0,BFLine(10,10)-(W,15),0,BFEnd SubPrivate Sub Timer1_Timer()Form1.Circle(BallX,BallY),4,&HC0C0C0 BallX=BallX+AddXBallY=BallY+AddYForm1.Circle(BallX,BallY),4,0If BallX<=20 Then AddX=-AddXIf BallY<=20 Then AddY=-AddYIf BallX>=W-10 Then AddX=-AddXIf BallY>=H-10 ThenIf BallXHitX+100 ThenTimer1.Enabled=FalseForm_PaintEnd IfAddY=-AddYEnd IfEnd Sub一旦程序代码输入完毕,你就可以按F5开始执行它,或是在File菜单里选取Make来生成EXE执行文件了,瞧,小球已经在你的屏幕上蹦来蹦去了。
怎么能让VB 程序最小化时在托盘显示呀急急急!~希望VB高手帮忙!
给你个例子吧建立一个frmmain主窗体Option ExplicitPrivate Sub Form_Load()'初始化imgIcon控件的Picture属性imgIcon.Picture = LoadPicture(App.Path & "\" & "heart.ico") mnuTrayShow.Enabled = False'初始化NOTIFYICONDATA数据结构Dim nid As NOTIFYICONDATAnid.cbSize = Len(nid)nid.hwnd = frmTemp.hwndnid.uId = 1&nid.uFlags = NIF_ICON Or NIF_TIP Or NIF_MESSAGE nid.uCallbackMessage = WM_NOTIFYICONnid.hicon = imgIcon.Picturenid.szTip = "系统托盘中的图标" & Chr(0)'调用Shell_NotifyIcon函数将图标加入到系统托盘中Shell_NotifyIcon NIM_ADD, nidEnd SubPrivate Sub Form_Unload(Cancel As Integer)'设置自定义类型的变量的内容Dim nid As NOTIFYICONDATAnid.cbSize = Len(nid)nid.hwnd = frmTemp.hwndnid.uId = 1&nid.uFlags = 0'调用Shell_NotifyIcon方法来删除系统托盘中的图标Shell_NotifyIcon NIM_DELETE, nidUnload frmTempEnd SubPrivate Sub mnuTrayExit_Click()Unload MeEnd SubPrivate Sub mnuTrayHide_Click()'隐藏窗体,并相应改变菜单项的状态Me.HidemnuTrayHide.Enabled = FalsemnuTrayShow.Enabled = TrueEnd SubPrivate Sub mnuTrayIcon_Click()'设置dlgOpen公用对话框的属性,以便取得相应的图标文件dlgOpen.Filter = "图标文件(*.ico)|*.ico"dlgOpen.Flags = cdlOFNFileMustExistdlgOpen.ShowOpenIf dlgOpen.FileName = "" Then Exit Sub'根据所取得图标文件,来改变imgIcon文件的属性imgIcon.Picture = LoadPicture(dlgOpen.FileName)'设置NOTIFYICONDATA数据结构Dim nid As NOTIFYICONDATAnid.cbSize = Len(nid)nid.hwnd = frmTemp.hwndnid.uId = 1&nid.uFlags = NIF_ICONnid.hicon = imgIcon.Picture'调用Shell_NotifyIcon函数来修改系统托盘中的图标Shell_NotifyIcon NIM_MODIFY, nidEnd SubPrivate Sub mnuTrayShow_Click()'显示窗体,并相应改变菜单项的状态Me.ShowmnuTrayHide.Enabled = TruemnuTrayShow.Enabled = FalseEnd SubPrivate Sub mnuTrayTip_Click()Dim str As Stringstr = InputBox("输入系统托盘中的图标的提示信息:", "提示信息") If str = "" Then Exit Sub'设置NOTIFYICONDATA数据结构Dim nid As NOTIFYICONDATAnid.cbSize = Len(nid)nid.hwnd = frmTemp.hwndnid.uId = 1&nid.uFlags = NIF_TIPnid.szTip = str & Chr(0)'调用Shell_NotifyIcon函数来修改系统托盘中的图标的提示Shell_NotifyIcon NIM_MODIFY, nidEnd Sub再建立一个空窗体叫frmTemp再建一个模块,名字随便了Option Explicit'声明Shell_NotifyIcon函数,用于将图标加入到系统托盘中Public Declare Function Shell_NotifyIcon Lib "shell32" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, pnid As NOTIFYICONDATA) As Boolean'声明自定义的数据类型NOTIFYICONDATAPublic Type NOTIFYICONDATAcbSize As Longhwnd As LonguId As LonguFlags As LonguCallbackMessage As Longhicon As LongszTip As String * 64End Type'声明常量Public Const NIM_ADD = &H0Public Const NIM_MODIFY = &H1Public Const NIM_DELETE = &H2Public Const NIF_MESSAGE = &H1Public Const NIF_ICON = &H2Public Const NIF_TIP = &H4'定义SetWindowLong,用以改变frmTemp窗体的窗体函数Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long'定义事件的常数代码Public Const WM_LBUTTONDOWN = &H201Public Const WM_RBUTTONDOWN = &H204Public Const WM_USER = &H400'定义自定义的事件WM_NOTIFYICONPublic Const WM_NOTIFYICON = WM_USER + &H100'替换窗口处理函数Public Const GWL_WNDPROC = (-4)'该函数为frmTest的窗体处理函数。
VB系统托盘及菜单
VB系统托盘及菜单'模块声明Option ExplicitPublic Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As LongPublic Const NIM_ADD = &H0Public Const NIM_DELETE = &H2Public Const NIF_ICON = &H2Public Const NIF_MESSAGE = &H1Public Const NIF_TIP = &H4Public Type NOTIFYICONDATAcbSize As Longhwnd As LonguID As LonguFlags As LonguCallbackMessage As LonghIcon As LongszTip As String * 64End TypePublic Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As LongPublic 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 LongPublic Const GWL_WNDPROC = (-4)Public Const WM_USER = &H400Public Const WM_TRAYICON = WM_USER + 123 '托盘消息Public Const WM_LBUTTONDOWN As Long = &H201Public Const WM_LBUTTONUP As Long = &H202Public Const WM_RBUTTONDOWN = &H204Public Const WM_RBUTTONUP = &H205Public Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long'====================================== =====Public pWndProc As LongPublic Function WndProc(ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long If Msg = WM_TRAYICON ThenSelect Case lParamCase WM_RBUTTONDOWNSetForegroundWindow hwnd '关键的一步Case WM_RBUTTONUPForm1.PopupMenu Form1.Mnu_MenuCase WM_LBUTTONDOWNSetForegroundWindow hwnd '关键的一步Case WM_LBUTTONUPIf Form1.Visible = True ThenForm1.HideElseForm1.ShowEnd IfEnd SelectEnd IfWndProc = CallWindowProc(pWndProc, hwnd, Msg, wParam, lParam)End Function'Form 主窗口'需要的空件:Mnu_SubMenu,MnuMenuOption ExplicitPrivate lpTrayIconData As NOTIFYICONDATAPrivate Sub Form_Load()With lpTrayIconData.cbSize = Len(lpTrayIconData).hIcon = Me.Icon.Handle.hwnd = Me.hwnd.szTip = "托盘消息演示" & vbNullChar.uFlags = NIF_MESSAGE Or NIF_ICON Or NIF_TIP.uCallbackMessage = WM_TRAYICON.uID = 0End WithMe.HideShell_NotifyIcon NIM_ADD, lpTrayIconDatapWndProc = SetWindowLong(Me.hwnd, GWL_WNDPROC, AddressOf WndProc)End Sub'子菜单命令Private Sub Form_Unload(Cancel As Integer)Shell_NotifyIcon NIM_DELETE, lpTrayIconDataSetWindowLong Me.hwnd, GWL_WNDPROC, pWndProcEnd SubPrivate Sub Mnu_SubMenu_Click(Index As Integer)Select Case IndexCase "0"MsgBox Mnu_SubMenu(Index).CaptionEnd SelectEnd Sub。
VB实现在窗口的标题栏上添加一个按钮的功能实现程序最小化到系统托盘
程序运行窗口在窗口的标题栏上添加了一个按钮,实现最小化到系统托盘右键菜单1、复制以下程序段到记事本中另存为文件:Type=ExeReference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\WINDOWS\system32\std ole2.tlb#OLE AutomationModule=TrayStartup="frmMain"HelpFile=""ExeName32="Project1.exe"Path32="..\..\..\..\..\..\WINDOWS\Desktop"Command32=""Name="Project1"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=0RevisionVer=0AutoIncrementVer=0ServerSupportFiles=0VersionCompanyName="None"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0 FlPointCheck=0 FDIVCheck=0 UnroundedFP=0 StartMode=0 Unattended=0 Retained=0 ThreadPerObject=0 MaxNumberOfThreads=1[MS Transaction Server] AutoRefresh=1Begin VB.Form frmMainAutoRedraw = -1 'TrueCaption = "TitleBar Tray Button Demo"ClientHeight = 2040ClientLeft = 60ClientTop = 345ClientWidth = 4680LinkTopic = "Form1"ScaleHeight = 2040ScaleWidth = 4680StartUpPosition = 3 '窗口缺省Begin VB.Menu mnuPopUpCaption = ""Visible = 0 'FalseBegin VB.Menu mnuRestoreCaption = "Restore"EndEndEndAttribute VB_Name = "frmMain"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalsePrivate Sub Form_Load()Print "Right Click For Menu"Me.ScaleMode = vbPixels 'The API works in pixelsHook Me 'FormHook Hook()End SubPrivate Sub Form_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)If Button = 2 Then TrayMenu Me 'TrayNotify TrayMneu()End SubPrivate Sub Form_Unload(Cancel As Integer)UnHook 'FormHook UnHook()End SubAttribute VB_Name = "ToolTip"Const WS_EX_TOPMOST = &H8&Const TTS_ALWAYSTIP = &H1Const HWND_TOPMOST = -1Const SWP_NOACTIVATE = &H10Const SWP_NOMOVE = &H2Const SWP_NOSIZE = &H1Const WM_USER = &H400Const TTM_ADDTOOLA = (WM_USER + 4)Const TTF_SUBCLASS = &H10Declare Function CreateWindowEx Lib "user32" Alias "CreateWindowExA" (ByVal dwExStyle As Long, ByVal lpClassName As String, ByVal lpWindowName As String, ByVal dwStyle As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hWndParent As Long, ByVal hMenu As Long, ByVal hInstance As Long, lpParam As Any) As Long Declare Function DestroyWindow Lib "user32" (ByVal hwnd As Long) As Long 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 LongPublic Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As LongType TOOLINFOcbSize As LonguFlags As Longhwnd As Longuid As LongRECT As RECThinst As LonglpszText As StringlParam As LongEnd TypePublic hWndTT As LongPublic Sub CreateTip(hwndForm As Long, szText As String, rct As RECT)hWndTT = CreateWindowEx(WS_EX_TOPMOST, "tooltips_class32", "",TTS_ALWAYSTIP, _0, 0, 0, 0, hwndForm, 0&, App.hInstance, 0&)SetWindowPos hWndTT, HWND_TOPMOST, 0, 0, 0, 0, _SWP_NOMOVE Or SWP_NOSIZE Or SWP_NOACTIVATEDim TI As TOOLINFOWith TI.cbSize = Len(TI).uFlags = TTF_SUBCLASS.hwnd = hwndForm.uid = 1&.lpszText = szText & vbNullChar.RECT = rctEnd WithSendMessage hWndTT, TTM_ADDTOOLA, 0, TIEnd SubPublic Sub KillTip()DestroyWindow hWndTTEnd Sub4、复制以下程序段到记事本中另存为文件:Attribute VB_Name = "DrawButton"Declare Function GetWindowDC Lib "user32" (ByVal hwnd As Long) As Long Declare Function DrawFrameControl Lib "user32" (ByVal hdc As Long, lpRect As RECT, ByVal un1 As Long, ByVal un2 As Long) As LongDeclare Function GetTitleBarInfo Lib "user32" (ByVal hwnd As Long, pti As TitleBarInfo) As BooleanDeclare Function FillRect Lib "user32" (ByVal hdc As Long, lpRect As RECT, ByVal hBrush As Long) As LongDeclare Function GetSysColorBrush Lib "user32" (ByVal nIndex As Long) As LongDeclare Function OffsetRect Lib "user32" (lpRect As RECT, ByVal x As Long, ByVal y As Long) As LongType RECTLeft As LongTop As LongRight As LongBottom As LongEnd TypeType TitleBarInfocbSize As LongrcTitleBar As RECT 'A RECT structure that receives the coordinates of the title barrgState(5) As Long 'An array that receives a DWORD value for each element of the title barEnd Type'rgState array Values'0 The titlebar Itself'1 Reserved'2 Min button'3 Max button'4 Help button'5 Close button''rgstate return constatnts'STATE_SYSTEM_FOCUSABLE = &H00100000'STATE_SYSTEM_INVISIBLE = &H00008000'STATE_SYSTEM_OFFSCREEN = &H00010000'STATE_SYSTEM_PRESSED = &H00000008'STATE_SYSTEM_UNAVAILABLE = &H00000001Const DFC_BUTTON = 4Const DFCS_BUTTONPUSH = &H10Const DFCS_PUSHED = &H200Declare Function GetSystemMetrics Lib "user32" (ByVal nIndex As Long) As LongPublic Declare Function PtInRect Lib "user32" (lpRect As RECT, ByVal x As Long, ByVal y As Long) As LongPublic Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As LongPublic Type POINTAPIx As Longy As LongEnd TypeConst SM_CXFRAME = 32Const COLOR_BTNTEXT = 18Dim lDC As LongPublic R As RECTPublic Sub ButtonDraw(frm As Form, bState As Boolean)Dim TBButtons As IntegerDim TBarHeight As IntegerDim TBButtonHeight As IntegerDim TBButtonWidth As IntegerDim DrawWidth As IntegerDim TBI As TitleBarInfoDim TBIRect As RECTDim bRslt As BooleanDim WinBorder As IntegerWith frmIf .BorderStyle = 0 Then Exit Sub ' Don't draw a button if there is no titlebar'----How Many Buttons in TitleBar------------------------------------------If Not .ControlBox Then TBButtons = 0If .ControlBox Then TBButtons = 1If .ControlBox And .WhatsThisButton ThenIf .BorderStyle < 4 ThenTBButtons = 2ElsetButtons = 1End IfEnd IfIf .ControlBox And .MinButton And .BorderStyle = 2 Then TBButtons = 3If .ControlBox And .MinButton And .BorderStyle = 5 Then TBButtons = 1If .ControlBox And .MaxButton And .BorderStyle = 2 Then TBButtons = 3If .ControlBox And .MaxButton And .BorderStyle = 5 Then TBButtons = 1'------------------------------------------------------------------------'----Get height of Titlebar----------------------------------------------'Using this method gets the height of the titlebar regardless of the window'style. It does, however, restrict its use to Win98/2000. So if you want to'use this code in Win95, then call GetSystemMetrics to find the windowstyle'and titlebar size.TBI.cbSize = Len(TBI)bRslt = GetTitleBarInfo(.hwnd, TBI)TBarHeight = TBIRect.Bottom - TBIRect.Top - 1'-----------------------------------------------------------------------'----Get WindowBorder Size----------------------------------------------If .BorderStyle = 2 Or .BorderStyle = 5 ThenR.Top = GetSystemMetrics(32) + 2WinBorder = R.Top - 6ElseR.Top = 5WinBorder = -1End IfEnd With'---------------------------------------------------------------------------'----Use Titlebar Height to determin button size----------------------------TBButtonHeight = TBarHeight - 4TBButtonWidth = TBButtonHeight + 2'and the size and space of the dot on the buttonDrawWidth = TBarHeight / 8'---------------------------------------------------------------------------'----Determin the position of our button------------------------------------R.Bottom = R.Top + TBButtonHeightSelect Case TBButtonsCase 1R.Right = frm.ScaleWidth - (TBButtonWidth) + WinBorderCase 2R.Right = frm.ScaleWidth - ((TBButtonWidth * 2) + 2) + WinBorderCase 3R.Right = frm.ScaleWidth - ((TBButtonWidth * 3) + 2) + WinBorderCase ElseEnd SelectR.Left = R.Right - TBButtonWidth'--------------------------------------------------------------------------'----Get the Widow DC so that we may draw in the title bar-----------------lDC = GetWindowDC(frm.hwnd)'--------------------------------------------------------------------------'----Determin the position of thedot--------------------------------------Dim StartXY As Integer, EndXY As IntegerSelect Case TBarHeightCase Is < 20StartXY = DrawWidth + 1EndXY = DrawWidth - 1Case ElseStartXY = (DrawWidth * 2)EndXY = DrawWidthEnd Select'--------------------------------------------------------------------------'----We have all the information we need So Draw the button----------------Dim rDot As RECTIf bState ThenDrawFrameControl lDC, R, DFC_BUTTON, DFCS_BUTTONPUSH Or DFCS_PUSHEDrDot.Left = R.Right - (1 + StartXY): rDot.Top = R.Bottom - (1 + StartXY)rDot.Right = R.Right - (1 + EndXY): rDot.Bottom = R.Bottom - (1 + EndXY)ElseDrawFrameControl lDC, R, DFC_BUTTON, DFCS_BUTTONPUSHrDot.Left = R.Right - (2 + StartXY): rDot.Top = R.Bottom - (2 + StartXY)rDot.Right = R.Right - (2 + EndXY): rDot.Bottom = R.Bottom - (2 + EndXY)End IfFillRect lDC, rDot, GetSysColorBrush(COLOR_BTNTEXT)'---------------------------------------------------------------------------'----SetTooltip------------------------------------------------------------ Dim TTRect As RECTTTRect.Bottom = R.Bottom + (TBarHeight - ((TBarHeight * 2) + WinBorder + 5))TTRect.Left = R.Left - (4 - WinBorder)TTRect.Right = R.Right - (4 - WinBorder)TTRect.Top = R.Top + (TBarHeight - ((TBarHeight * 2) + WinBorder + 5))KillTip 'ToolTip KillTip()CreateTip appForm.hwnd, "System Tray", TTRect 'ToolTip CreateTip()End Sub5、复制以下程序段到记事本中另存为文件:Attribute VB_Name = "TrayNotify"Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As LongDeclare Function CreatePopupMenu Lib "user32" () As LongDeclare Function TrackPopupMenu Lib "user32" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal x As Long, ByVal y As Long, ByVal nReserved As Long, ByVal hwnd As Long, ByVal lprc As Any) As LongDeclare Function AppendMenu Lib "user32" Alias "AppendMenuA" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long, ByVal lpNewItem As Any) As LongDeclare Function DestroyMenu Lib "user32" (ByVal hMenu As Long) As LongType NOTIFYICONDATAcbSize As Longhwnd As Longuid As LonguFlags As LonguCallbackMessage As LonghIcon As Longsztip As String * 64End TypeConst NIM_ADD = &H0Const NIM_DELETE = &H2Const NIM_MODIFY = &H1Const NIF_MESSAGE = &H1Const NIF_ICON = &H2Const NIF_TIP = &H4Const MF_GRAYED = &H1&Const MF_STRING = &H0&Const MF_SEPARATOR = &H800&Const TPM_NONOTIFY = &H80&Const TPM_RETURNCMD = &H100&Public bTraySet As BooleanDim lMenu As LongPublic Sub TraySet(frm As Form, sztip As String, hIcon As Long)Dim NID As NOTIFYICONDATAWith NID.cbSize = Len(NID).hIcon = hIcon.sztip = sztip & vbNullChar.uCallbackMessage = WM_LBUTTONUP.uFlags = NIF_MESSAGE Or NIF_ICON Or NIF_TIP .uid = 1&End WithShell_NotifyIcon NIM_ADD, NIDbTraySet = TrueEnd SubPublic Sub TrayRestore(frm As Form)Dim NID As NOTIFYICONDATAWith NID.cbSize = Len(NID).uid = 1&End WithShell_NotifyIcon NIM_DELETE, NIDbTraySet = FalseEnd SubPublic Sub TrayMenu(frm As Form)Dim hMenu As Long, tMenu As LongDim MP As POINTAPIGetCursorPos MPhMenu = CreatePopupMenu()If bTraySet ThenAppendMenu hMenu, MF_STRING, 1000, "Restore" ElseAppendMenu hMenu, MF_STRING Or MF_GRAYED, 1000, "Restore"End IfAppendMenu hMenu, MF_SEPARATOR, 0&, 0&AppendMenu hMenu, MF_STRING, 1010, "Exit"tMenu = TrackPopupMenu(hMenu, TPM_NONOTIFY Or TPM_RETURNCMD, MP.x, MP.y, 0&, frm.hwnd, 0&)Select Case tMenuCase 1000TrayRestore frmCase 1010TrayRestore frmUnHookUnload frmCase Else'do nothingEnd SelectDestroyMenu hMenuEnd Sub6、复制以下程序段到记事本中另存为文件:Attribute VB_Name = "FormHook"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 LongDeclare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" _ (ByVal hwnd As Long, _ByVal nIndex As Long, _ByVal dwNewLong As Long) As LongDeclare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As IntegerPublic Const GWL_WNDPROC = -4Public Const WM_LBUTTONDOWN = &H201Public Const WM_LBUTTONUP = &H202Public Const WM_MOUSEMOVE = &H200Public Const WM_NCMOUSEMOVE = &HA0Public Const WM_NCLBUTTONDOWN = &HA1Public Const WM_NCLBUTTONUP = &HA2Public Const WM_NCLBUTTONDBLCLK = &HA3Public Const WM_NCRBUTTONDOWN = &HA4Public Const WM_NCRBUTTONUP = &HA5Public Const WM_ACTIVATE = &H6Public Const WM_NCPAINT = &H85Public Const WM_PAINT = &HFPublic Const WM_ACTIVATEAPP = &H1CPublic Const WM_MOUSEACTIVATE = &H21Public Const WM_COMMAND = &H111Public Const WM_NCACTIVATE = &H86Public Const WM_DESTROY = &H2Public Const WM_SIZE = &H5Global lpPrevWndProc As LongGlobal gHW As LongGlobal appForm As FormPrivate Function MakePoints(lParam As Long) As POINTAPIDim hexstr As Stringhexstr = Right("00000000" & Hex(lParam), 8)MakePoints.x = CLng("&H" & Right(hexstr, 4)) - (appForm.Left / Screen.TwipsPerPixelX)MakePoints.y = CLng("&H" & Left(hexstr, 4)) - (appForm.Top / Screen.TwipsPerPixelY)End FunctionPublic Sub Hook(frm As Form)Set appForm = frmlpPrevWndProc = SetWindowLong(gHW, GWL_WNDPROC, AddressOf WindowProc)End SubPublic Sub UnHook()Dim lngReturnValue As LonglngReturnValue = SetWindowLong(gHW, GWL_WNDPROC, lpPrevWndProc) End SubFunction WindowProc(ByVal hwnd As Long, _ByVal uMsg As Long, _ByVal wParam As Long, _ByVal lParam As Long) As Long'------------------------------------------------------------------------------'Messing around in here can cause allsorts of problems.'So, if you must, make sure you save everytihing you want to keep 'before you run the program.'Don't run anything outside of a message selection as it will be 'executed so many times per second that it will slow down system response.Dim lRslt As LongDim retProc As BooleanStatic STButtonState As BooleanStatic Toggle As BooleanStatic i As IntegerOn Error Resume NextSelect Case uMsgCase WM_DESTROYTrayRestore appFormKillTip 'ToolTip KillTip()UnHookretProc = TrueCase WM_NCMOUSEMOVE'Only draw the button when necessaryIf GetAsyncKeyState(vbLeftButton) < 0 ThenIf OverButton(lParam) ThenIf Toggle = False ThenToggle = TrueButtonDraw appForm, Toggle 'DrawButton ButtonDraw()End IfElseIf Toggle = True ThenToggle = FalseButtonDraw appForm, Toggle 'DrawButton ButtonDraw()End IfEnd IfElseSTButtonState = FalseretProc = TrueEnd IfCase WM_NCLBUTTONDOWNIf OverButton(lParam) ThenSTButtonState = TrueButtonDraw appForm, True 'DrawButton ButtonDraw()ElseSTButtonState = FalseretProc = TrueEnd IfCase WM_NCLBUTTONUPSTButtonState = FalseIf OverButton(lParam) ThenTraySet appForm, appForm.Caption, appForm.Icon'TrayNotify TraySet()ButtonDraw appForm, False 'DrawButton ButtonDraw()retProc = FalseElseretProc = TrueEnd IfCase WM_LBUTTONUPSTButtonState = FalseButtonDraw appForm, False 'DrawButton ButtonDraw()If GetAsyncKeyState(vbLeftButton) < 0 And bTraySet Then TrayMenu appForm 'TrayNotify TrayMenu()End IfretProc = TrueCase WM_NCLBUTTONDBLCLK, WM_NCRBUTTONDOWNIf Not OverButton(lParam) ThenretProc = TrueEnd IfCase WM_SIZE, WM_NCPAINT, WM_PAINT, WM_COMMANDButtonDraw appForm, False 'DrawButton ButtonDraw()retProc = TrueCase WM_ACTIVATEAPP, WM_NCACTIVATE, WM_ACTIVATE, WM_MOUSEACTIVATEButtonDraw appForm, False 'DrawButton ButtonDraw()retProc = TrueCase ElseretProc = TrueEnd SelectIf retProc ThenWindowProc = CallWindowProc(lpPrevWndProc, hwnd, uMsg, wParam, lParam)ElseWindowProc = 0End IfEnd FunctionPrivate Function OverButton(lParam As Long) As Boolean Dim MP As POINTAPIMP = MakePoints(lParam)If PtInRect(R, MP.x, MP.y) Then OverButton = True End Function双击工程文件:运行,就可以看到效果。
vb系统托盘资料
VB托盘程序详解很多软件运行时会在系统托盘区(就是桌面右下角显示时间的区域)出现一个小图标,它作为程序运行的一个标志,我们可以通过使用小图标所弹出的菜单来控制应用程序的状态。
本例就给出了一个功能比较完整的托盘程序,我们可以看到怎样用API函数Shell_NotifyIcon来添加、删除、更改托盘图标;而且例中还演示了为托盘图标添加右键菜单和浮动提示的方法。
程序(附后)用到了Shell_NotifyIcon、SendMessage、CallWindowProc、SetWindowLong 等API函数,其中Shell_NotifyIcon是主要的函数,它用来添加、删除、更改系统托盘区(taskbar status area)的图标,所以我们先来看看这个函数的声明和参数:使用API函数之前必须先在程序中声明如下:Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA"(ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long其中各参数的意义如下表:参数: 意义dwMessage 为消息设置值,它可以是以下的几个常数值:0、1、2NIM_ADD = 0 加入图标到系统状态栏中NIM_MODIFY = 1 修改系统状态栏中的图标NIM_DELETE = 2 删除系统状态栏中的图标LpData 用以传入NOTIFYICONDATA数据结构变量,其结构如下所示:Type NOTIFYICONDATAcbSize As Long 需填入NOTIFYICONDATA数据结构的长度 HWnd As Long 设置成窗口的句柄Uid As Long 为图标所设置的ID值UFlags As Long 设置uCallbackMessage,hIcon,szTip是否有效UCallbackMessage As Long 消息编号HIcon As Long 显示在状态栏上的图标SzTip As String * 64 提示信息End Type返回值 Long,非零表示成功,零表示失败在使用这个API函数之前我们应该先定义结构类型NOTIFYICONDATA:Public Type NOTIFYICONDATAcbSize As Long HWnd As LongUid As Long UFlags As LongUCallbackMessage As LongHIcon As LongSzTip As String * 64End Type然后定义一个NOTIFYICONDATA的变量TheData来记录设置托盘图标的数据Private TheData As NOTIFYICONDATA这时我们就可以使用这个函数来设置系统托盘图标了,具体方法如下:1、添加图标With TheData.Uid = 0.HWnd = frm.HWnd 'frm.HWnd是程序主窗体的句柄.cbSize = Len(TheData).HIcon = frm.Icon.Handle 'frm.Icon.Handle指向主窗体的图标.UFlags = NIF_ICON.UCallbackMessage = TRAY_CALLBACK'作用是允许返回消息,在下一节中会有详细解释。
VB代码VB小程序:在系统托盘为程序添加图标
VB代码VB小程序:在系统托盘为程序添加图标当前位置:首页> VB小程序1-99 > 在系统托盘为程序添加图标20. 在系统托盘为程序添加图标本人原创,转载请注明出处:/100bd/blog/item/330b4d88ab0fa0b80e244455.html为程序在系统托盘中添加图标,要解决两个问题:一、调用 API 函数 Shell_NotifyIcon 添加图标,设置正确的参数。
程序结束时,从系统托盘删除添加的图标。
二、拦截窗口的回调函数,响应用户在系统托盘图标上的鼠标事件,一般是弹出快捷菜单。
自定义的回调函数不能放在窗体代码中,必须在模块中。
编写有关窗口回调函数的程序,最大的难点在于调试。
调试时,如果在窗口回调函数过程的执行期间设置断点,轻则影响窗口的自动重画,重则使程序停止响应。
因此,修改代码后应注意及时保存。
下面是实现在系统托盘为程序添加图标的完整代码,包括一个窗体和一个模块:'■■以下是窗体 Form1 的代码 ------------------------------------' 1.为窗体添加菜单' 为窗体添加菜单: mFast' 为 mFast 添加下级子菜单 mmFast,并将 mmFast 的索引设置为 0' 2.在窗体上添加四个控件,所有控件均采用默认设置:' Label1,Command1,Command2,Command3Dim ctTrayIco As NotifyIconDataPrivate Sub Form_Load()Me.Caption = "系统托盘例子"'为数组菜单 mmFast 添加条目mFast.Visible = FalseLoadKjZu mmFast, "显示 " & Me.Caption & "(&R)", "mmFast-Run"LoadKjZu mmFast, "最小化窗口(&N)", "mmFast-Min"LoadKjZu mmFast, "菜单例子 1 (&A)", "mmFast-A"LoadKjZu mmFast, "菜单例子 2 (&B)", "mmFast-B"LoadKjZu mmFast, "-" '菜单分隔条LoadKjZu mmFast, "退出(X)", "mmFast-Exit"Dim S As SingleLabel1.AutoSize = True: S = Label1.HeightLabel1.Caption = Me.Caption: Label1.Move S, SCommand1.Caption = "添加到系统托盘": Command1.Move S, S * 3, S * 11, S * 2Command2.Caption = "最小化到系统托盘": Command2.Move S, S * 6, S * 11, S * 2Command3.Caption = "从系统托盘删除图标": Command3.Move S, S * 9, S * 11, S * 2'将窗口函数的地址设置为模块中的 WndProc 过程,当用户'在系统托盘图标单击鼠标右键时,弹出自定义的菜单 mFastWinAddress Me.hWnd''如果需要程序一启动就添加到系统托盘,解除下面语句的注释即可'Call SysTrayEnd SubPrivate Sub Form_Resize()'设置快捷菜单的是否可用状态Dim nEnabled As BooleanOn Error Resume NextnEnabled = Me.WindowState = vbMinimizedmmFast(KjZuIndex(mmFast, "mmFast-Min")).Enabled = nEnabledmmFast(KjZuIndex(mmFast, "mmFast-Run")).Enabled = Not nEnabled End SubPrivate Sub Form_Unload(Cancel As Integer)SysTray True '退出时,从系统托盘删除本程序图标WinAddress Me.hWnd, True '退出时,将窗口地址还原End SubPrivate Sub LoadKjZu(Kj As Object, nCap As String, Optional nTag As String)'为数组控件添加一个成员Dim I As LongI = Kj.UBoundIf Kj(I).Tag <> "" ThenI = I + 1Load Kj(I): Kj(I).Visible = TrueEnd IfKj(I).Caption = nCapIf nCap = "-" Then Kj(I).Tag = "bar" Else Kj(I).Tag = nTag End SubPrivate Function KjZuIndex(Kj As Object, nTag As String) As Long'返回数组控件中 Tag 属性为 nTag 的成员索引,没有找到返回 -1Dim I As LongFor I = Kj.LBound To Kj.UBoundIf Kj(I).Tag <> nTag Then KjZuIndex = I: Exit FunctionNextKjZuIndex = -1End FunctionPrivate Sub mmFast_Click(Index As Integer)'系统托盘快捷菜单Dim nCmd As StringnCmd = Trim(mmFast(Index).Tag)Select Case UCase(nCmd)Case UCase("mmFast-Run"): Call WinNormal '正常显示主窗口Case UCase("mmFast-Min"): Call WinMinimized '缩小到系统托盘Case UCase("mmFast-Exit"): Unload Me '退出程序Case UCase("mmFast-A"): MsgBox "这是系统托盘快捷菜单:mmFast-A", vbInformation, Me.Caption'Case UCase("mmFast-B")Case Else: MsgBox "此命令在“mmFast_Click”中无效:" & vbCrLf & vbCrLf & "nCmd = " & nCmd, vbInformati on, Me.Caption & " - 无效命令"End SelectEnd SubPrivate Sub Command1_Click()Call SysTray '添加到系统托盘End SubPrivate Sub Command2_Click()Call WinMinimized '缩小到系统托盘End SubPrivate Sub Command3_Click()Call SysTray(True) '从系统托盘删除本程序图标End SubPrivate Sub WinNormal()'正常显示主窗口Me.Visible = TrueDoEventsMe.WindowState = 0End SubPrivate Sub WinMinimized()'缩小到系统托盘Me.WindowState = vbMinimizedCall SysTray: Me.Visible = FalseLabel1.Caption = "缩小到系统图标"End SubPrivate Sub SysTray(Optional IcoDel As Boolean)'在系统托盘为本程序添加图标Dim dl As LongIf IcoDel Thendl = Shell_NotifyIcon(NIM_DELETE, ctTrayIco)If dl = 0 ThenLabel1.Caption = "从系统托盘删除图标,失败" ElseLabel1.Caption = "已从系统托盘删除图标,成功" End IfExit SubEnd IfctTrayIco.cbSize = Len(ctTrayIco)ctTrayIco.hWnd = Me.hWndctTrayIco.uID = SysTray_IDctTrayIco.uFlags = NIF_MESSAGE + NIF_ICON + NIF_TIP ctTrayIco.uCallbackMessage = WM_TrayctTrayIco.hIcon = Me.Icon.HandlectTrayIco.szTip = "我的系统托盘图标" & Chr(0)dl = Shell_NotifyIcon(NIM_ADD, ctTrayIco)If dl = 0 ThenLabel1.Caption = "图标添加到系统托盘,失败" ElseLabel1.Caption = "图标已添加到系统托盘,成功" End IfEnd Sub'■■以下是模块代码 ------------------------------------Public Type NotifyIconDatacbSize As Long '结构大小,设置为:Len(NotifyIconData)hWnd As Long '建立托盘图标窗体的句柄uID As Long '托盘图标 ID 标识uFlags As Long '对图标的操作方式:uCallbackMessage As Long '回调函数消息编号,设置为:WM_USER + ?hIcon As Long '图标 Handle,设置为:Me.Icon.HandleszTip As String * 64 '图标提示信息,设置为:"字符串" & Chr(0)End TypePublic Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_N otifyIconA" (ByVal dwMessage As Long, lpData As NotifyIconData) As LongPublic Const SysTray_ID = 1Public Const NIM_ADD = &H0Public Const NIM_DELETE = &H2Public Const NIM_MODIFY = &H1Public Const NIF_MESSAGE = &H1Public Const NIF_ICON = &H2Public Const NIF_TIP = &H4Public Const WM_USER = &H400Public Const WM_Tray = WM_USER + 2Private Declare Function CallWindowProc Lib "user32" Alias "CallWindo wProcA" (ByVal lpPrevWndFunc As Long, ByVal hWnd As Long, ByVal Msg As Long, ByV al wParam As Long, ByVal lParam As Long) As LongPrivate Declare Function GetWindowLong Lib "user32" Alias "GetWind owLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As LongPrivate Declare Function SetWindowLong Lib "user32" Alias "SetWindo wLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As L ongPublic Const GWL_WNDPROC = (-4)Public Const WM_KEYDOWN = &H100Public Const WM_KEYUP = &H101Public Const WM_CHAR = &H102Public Const WM_SYSKEYDOWN = &H104Public Const WM_SYSKEYUP = &H105Public Const WM_SYSCHAR = &H106Public Const WM_MOUSEMOVE = &H200Public Const WM_LBUTTONDOWN = &H201Public Const WM_LBUTTONUP = &H202Public Const WM_RBUTTONDOWN = &H204Public Const WM_RBUTTONUP = &H205Dim moProc As LongPublic Function WndProc(ByVal hWnd As Long, ByVal Msg As Long, ByVal wParam As Lon g, ByVal lParam As Long) As Long'这是自定义的窗口回调函数。
使用VB实现系统托盘图标操作及一个有日历记事功能的实例
使用VB实现系统托盘图标操作及一个有日历记事功能的实例张庆
【期刊名称】《电脑编程技巧与维护》
【年(卷),期】2003(000)006
【摘要】本文对如何使用VB6.O通过调用Windows AIP函数,实现应用程序图标加入到Windows系统托盘和利用图标控制程序做了较为详细的介绍,并给出了一个应用程序实例来体现其具体实现过程.同时还讲解了VB6.0利用Monthview控件及Data控件实现日历记事和事件提醒功能的方法.
【总页数】5页(P21-25)
【作者】张庆
【作者单位】无
【正文语种】中文
【中图分类】TP3
【相关文献】
1.利用VBA实现宏操作实例 [J], 王丽;张桂香;李君
2.使用VBA技术实现办公自动化实例一二 [J], 陈迪;裴朋
3.利用VBA扩展Microsoft Word功能的一个实例--Microsoft Word学科插件[J], 蒋长根;黄明和
4.利用日历记事软件实现药品效期自动化管理 [J], 刘岩
5.不只是日历--一个基于浏览器的多功能日历 [J],
因版权原因,仅展示原文概要,查看原文内容请购买。
VB中控件拖放操作的教学研究
VB中控件拖放操作的教学研究在VB教学中,拖放操作是一个难点内容。
本文介绍在教学过程中如何讲解通过修改拖放坐标和使用API函数,实现在不同容器之间拖放控件的操作,并给出了实例程序。
关键词:VB;拖放;坐标;API函数在Visual Basic应用程序中,为了实现更加灵活的用户控制,时常需要由用户自己安排一些控件的位置。
在Windows操作系统中,经常使用拖动操作移动或复制文件;在一些应用程序中,可将工具栏中的控件按钮拖放到文档窗口中,实现插入对象操作;在Office软件中,还可以随意定制工具栏中的按钮。
在我多年的VB一线教学实践中,发现拖放操作的讲解难点在于拖放的目标位置设置。
在拖放控件时,根据源位置和目标位置的容器控件不同分为两种情况:在同一容器对象中拖放控件,在不同容器对象中拖放控件。
学生对于在不同容器中拖放控件有很多疑问,因此我在教学中采用了由浅入深、循序渐进的方法,分别讲解这两种情况的处理方法,并通过典型的实例让学生掌握拖放操作的相关概念和实现方法,收到了不错的效果,学生感觉比较容易理解,下面具体介绍一下这两种情况拖放操作的实现方法。
1在同一容器内部拖放控件在教学过程中,我首先讲解拖放操作的相关概念,然后举例介绍与拖放操作相关的属性、方法和事件。
拖放(Drag)操作是指在窗体中,将鼠标指针指向控件,按住鼠标按键移动鼠标,到达目标位置后松开鼠标按键,被拖放的控件移动到目标位置[1]。
在同一容器中拖放控件比较容易实现,可以通过设置控件的拖放属性,或调用控件的Drag方法来实现。
在教学过程中以命令按钮(CommandButton)控件为例,在窗体上添加一个命令按钮Command1,设置DragMode属性为1-Automatic (自动拖放),运行程序后用鼠标左键拖动命令按钮,可以看到拖动时显示灰色控件边框,但控件并不真正移动到目标位置。
若设置DragMode属性为0-Manual (手动拖放),则需要编写命令按钮的MouseDown事件调用其Drag方法,事件过程的代码如下:Private Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)Command1.Drag 1 …开始拖动控件End Sub运行程序时演示拖放操作,让学生看到两种设置方法的效果相同,使学生了解DragMode属性的含义和Drag方法的用法。
vb实现托盘(含程序)
VB托盘我按照下面的方法建了一个VB程序,可是在我自己的电脑上可以托盘,但换了电脑在别人的电脑上运行就没有托盘了,怎么回事啊!1、新建立一个VB6工程,将Form1的ShowInTaskBar属性设置为False2、菜单:工程--添加模块按“打开”这样就添加了一个新模块,名为Module1,保存为Module1.bas3、在Module1中写下如下代码:Option ExplicitPublic Const MAX_TOOLTIP As Integer = 64Public Const NIF_ICON = &H2Public Const NIF_MESSAGE = &H1Public Const NIF_TIP = &H4Public Const NIM_ADD = &H0Public Const NIM_DELETE = &H2Public Const WM_MOUSEMOVE = &H200Public Const WM_LBUTTONDOWN = &H201Public Const WM_LBUTTONUP = &H202Public Const WM_LBUTTONDBLCLK = &H203Public Const WM_RBUTTONDOWN = &H204Public Const WM_RBUTTONUP = &H205Public Const WM_RBUTTONDBLCLK = &H206Public Const SW_RESTORE = 9Public Const SW_HIDE = 0Public nfIconData As NOTIFYICONDATAPublic Type NOTIFYICONDATAcbSize As LonghWnd As LonguID As LonguFlags As LonguCallbackMessage As LonghIcon As LongszTip As String * MAX_TOOLTIPEnd TypePublic Declare Function ShowWindow Lib "user32" (ByVal hWnd As Long, ByVal nCmdShow As Long) As LongPublic Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long'4、在Form1的Load事件中写下如下代码:Private Sub Form_Load()'以下把程序放入System Tray====================================System Tray BeginWith nfIconData.hWnd = Me.hWnd.uID = Me.Icon.uFlags = NIF_ICON Or NIF_MESSAGE Or NIF_TIP.uCallbackMessage = WM_MOUSEMOVE.hIcon = Me.Icon.Handle'定义鼠标移动到托盘上时显示的Tip.szTip = App.Title + "(版本" & App.Major & "." & App.Minor & "." & App.Revision & ")" & vbNullChar.cbSize = Len(nfIconData)End WithCall Shell_NotifyIcon(NIM_ADD, nfIconData)'=============================================================System Tray EndMe.HideEnd Sub'5、在Form1的QueryUnload事件中写入如下代码:Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)Call Shell_NotifyIcon(NIM_DELETE, nfIconData)End Sub'6、在Form1的MouseMove事件中写下如下代码:Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)Dim lMsg As SinglelMsg = X / Screen.TwipsPerPixelXSelect Case lMsgCase WM_LBUTTONUP'MsgBox "请用鼠标右键点击图标!", vbInformation, "实时播音专家"'单击左键,显示窗体ShowWindow Me.hWnd, SW_RESTORE'下面两句的目的是把窗口显示在窗口最顶层'Me.Show'Me.SetFocus'' Case WM_RBUTTONUP'' PopupMenu MenuTray '如果是在系统Tray图标上点右键,则弹出菜单MenuTray'' Case WM_MOUSEMOVE'' Case WM_LBUTTONDOWN'' Case WM_LBUTTONDBLCLK'' Case WM_RBUTTONDOWN'' Case WM_RBUTTONDBLCLK'' Case ElseEnd SelectEnd Sub7、现在将程序保存起来运行看看系统托盘处是否增加了一个本工程的图标。
托盘程序
静态托盘程序的编写过程往NotifyIcon实例中添加菜单,首先要创建ContextMenu实例,此实例主要作用是表示快捷菜单,其中的菜单项是通过创建MenuItem实例来实现,托盘程序中的菜单有几个菜单项,就创建几个MenuItem实例。
然后把这些菜单项加入到ContextMenu实例,并把此实例赋值给NotifyIcon实例的ContextMenu属性,这样托盘程序右键点击弹出的菜单就完成了。
下面是具体代码:创建ContextMenu实例和MenuItem实例:FriendWithEventsContextMenu1 As System.Windows.Forms.ContextMenu FriendWithEventsMenuItem1 As System.Windows.Forms.MenuItem FriendWithEventsMenuItem2 As System.Windows.Forms.MenuItem FriendWithEventsMenuItem3 As System.Windows.Forms.MenuItem把这些菜单项加入到ContextMenu实例,并把ContextMenu实例赋值给NotifyIcon实例的ContextMenu属性:Me.MenuItem1=NewSystem.Windows.Forms.MenuItem()Me.MenuItem2=NewSystem.Windows.Forms.MenuItem()Me.MenuItem3=NewSystem.Windows.Forms.MenuItem()Me.NotifyIcon1.ContextMenu=Me.ContextMenu1Me.NotifyIcon1.Text="的托盘程序"Me.NotifyIcon1.Visible=True'设定托盘程序托盘区位置显示图标Me.NotifyIcon1.Icon=TrayIcon'在ContextMenu实例中加入菜单项Me.ContextMenu1.MenuItems.Add(Me.MenuItem1)Me.ContextMenu1.MenuItems.Add(Me.MenuItem2)Me.ContextMenu1.MenuItems.Add(Me.MenuItem3)Me.MenuItem1.Index=0Me.MenuItem1.Text="显示窗体"Me.MenuItem2.Index=1Me.MenuItem2.Text="隐藏窗体"Me.MenuItem3.Index=2Me.MenuItem3.Text="退出"当把ContextMenu实例赋值给NotifyIcon实例的ContextMenu属性后,托盘程序的缺省状态是当鼠标右击托盘图标,就会弹出对应的菜单。
VB实现托盘完整代码
VB托盘完整代码'VB最小化到托盘(含托盘菜单)的方法很多,这里介绍的是最简洁的做法,使用cSysTray控件,该控件需要自己编译并添加。
'需要找到VB的安装盘(不是安装以后的目录)的COMMON\TOOLS\VB\UNSUPPRT\SYSTRAY目录,将Systray目录拷到硬盘上面并编译为ocx控件(编译前记得要先把只读属性修改掉,有时候会提示要先保存,直接保存。
),使用安装包安装的用户,可在VB安装包里找到。
'以下是代码'API发送按键函数。
Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long) Const KEYEVENTF_KEYUP = &H2’托盘菜单-退出选项'tuichu 为一菜单的名称'此处用API函数发送ALT+F1指令调用窗体退出菜单,因此窗体菜单-退出选项需设置快捷键ALT+F1Private Sub tuichu_Click()cSysTray1.InTray = False主程序.WindowState = vbNormal主程序.Visible = True主程序.SetFocuskeybd_event vbKeyControl, 0, 0, 0keybd_event vbKeyF1, 0, 0, 0keybd_event vbKeyControl, 0, KEYEVENTF_KEYUP, 0End sub'托盘弹出菜单Private Sub cSysTray1_MouseDown(Button As Integer, Id As Long)If Button = 2 Then PopupMenu tuopan, 10End Sub'最小化后归托盘Private Sub Form_Resize()If Me.WindowState = vbMinimized ThencSysTray1.InTray = TrueMe.Visible = FalseElse: cSysTray1.InTray = TrueEnd If'托盘菜单弹出主界面'zhujiemian 为一菜单项的名称Private Sub zhujiemian_Click()主程序.WindowState = vbNormal主程序.Visible = TrueEnd Sub'双击托盘菜单弹出主界面Private Sub cSysTray1_MouseDblClick(Button As Integer, Id As Long)主程序.WindowState = vbNormal主程序.Visible = True主程序.SetFocusEnd Sub'单击关闭不退出程序Private Sub Form_Unload(Cancel As Integer)主程序.HideCancel = FalseEnd Sub'单击关闭不退出程序Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer) Cancel = 1主程序.HideEnd Sub’tui为窗体菜单-退出选项名称Private Sub tui_Click()’快捷键设ALT+F1EndEnd Sub'注:"主程序"代表一个窗体(Form),窗体菜单-退出选项需设置快捷键ALT+F1 '这个控件有一个小小的问题,如果托盘菜单有退出选项,不能直接用"End 语句",否则在编译后运行期间用户选择退出后,操作系统会报错,以上使用发送按键方法避免出错,当然还有其他避免出错方法。
vb将程序最小化到托盘
Public Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As LongPublic Declare Function DrawIcon Lib "user32" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, ByVal hicon As Long) As LongPublic Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As LongPublic Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long Public Declare Function TrackPopupMenu Lib "user32" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal x As Long, ByVal y As Long, ByVal nReserved As Long, ByVal hwnd As Long, lprc As Any) As LongPublic Declare Function GetMenu Lib "user32" (ByVal hwnd As Long) As LongPublic Declare Function GetSubMenu Lib "user32" (ByVal hMenu As Long, ByVal nPos As Long) As LongPublic Type POINTAPIx As Longy As LongEnd TypePublic Type NOTIFYICONDATAcbSize As Long '结构的长度hwnd As Long '消息接收窗口的句柄uID As Long '图标的标识uFlags As Long '设置参数uCallbackMessage As Long '回调消息的值hicon As Long '图标句柄szTip As String * 64 '提示字符串End TypePublic Const NIM_ADD = 0 '添加图标Public Const NIM_MODIFY = 1 '修改图标Public Const NIM_DELETE = 2 '删除图标Public Const NIF_MESSAGE = 1 '当有鼠标事件发生时产生消息Public Const NIF_ICON = 2 'Public Const NIF_TIP = 4 '图标有提示字符串Public Const WM_LBUTTONDOWN = &H201Public Const WM_RBUTTONDOWN = &H204Public Const WM_USER = &H400Public Const WM_NOTIFYICON = WM_USER + &H100Public Const WM_COMMAND = &H111Public Const WM_DESTROY = &H2Public Const WM_DRA WITEM = &H2BPublic Const WM_INITDIALOG = &H110Public Const WM_PAINT = &HFPublic Const WM_MENUSELECT = &H11FPublic Const GWL_WNDPROC = (-4) '替换窗口处理函数Dim pmenu As LongDim submenu As LongGlobal lproc As LongFunction CMenu() As Boolean'这个函数获得Form1的子菜单Dim l As LongDim l1 As Longpmenu = GetMenu(Form1.hwnd)submenu = GetSubMenu(pmenu, 0)If submenu ThenCMenu = TrueElseCMenu = FalseEnd IfEnd FunctionFunction Icon_Del(ihwnd As Long) As LongDim ano As NOTIFYICONDATADim l As Longano.hwnd = ihwndano.uID = 0ano.cbSize = Len(ano)'删除图标Icon_Del = Shell_NotifyIcon(NIM_DELETE, ano)End Function'这个函数接收图标句柄和窗口句柄并且新建图标Function Icon_Add(ihwnd As Long, hicon As Long) As LongDim ano As NOTIFYICONDATADim astr As String'为图标添加提示行astr = LTrim$(InputBox$("Input the tips you wanted to add.")) ano.szTip = astr + Chr$(0)'设置消息接收窗口ano.hwnd = ihwndano.uID = 0'图标有提示并且可以发送消息ano.uFlags = NIF_ICON Or NIF_TIP Or NIF_MESSAGEano.hicon = hiconano.cbSize = Len(ano)'将图标的回调消息设置为WM_NOTIFYICON,当在图标区域有鼠标消息,系统就会向'消息接收窗口发送WM_NOTIFYICON消息。
用VisualBasic编写托盘程序
用VisualBasic编写托盘程序
崔佳宾
【期刊名称】《电子与电脑》
【年(卷),期】1998(5)9
【摘要】Windows 95、Windows 98、Windows NT等操作系统的界面上都增加了Shell层的技术,这就为广大编程人员开辟了界面编程的新途径。
本文讲述的是如何用VB 5.0来编写托盘程序。
托盘程序主要解决两个问题:(1)创建、修改、删除托盘;(2)如何对托盘接收到的消息进行处理。
这就要用到几个Win32 API。
首先,Shell_NotifyIcon是用于托盘的Shell API。
该API用到一个NOTIFYICONDATA结构,该结构包括:hIcon(托盘图标指针)。
【总页数】3页(P113-115)
【作者】崔佳宾
【作者单位】辽宁大连河口区凌北路11号管理推进室
【正文语种】中文
【中图分类】TP311
【相关文献】
1.如何用Delphi编写托盘程序 [J], 薛燕红
2.用VisualBasic编写控制程序方法 [J], 李晓辉;肖蓉晖
3.如何用Delphi编写托盘程序 [J], 薛燕红
4.VisualBasic在数控冲程序编写中的应用 [J],
5.使用PowerBuilder编写系统托盘程序 [J], 周伟;王丰
因版权原因,仅展示原文概要,查看原文内容请购买。
给VB应用程序制作托盘图标
关键 词 Wid w 托 盘 图标 AP 函数 no s I
M a ng Tr y I o f pplc i ns i VB ki a c n or A i ato n
LiJa g o in u
Ab t a t sr c Ke wo d y r Th s p p r i to c s t i a e n r du e he me o t s i d ws API n k s r y i o o p l a i n n VB h t d o ue W n o a d ma e t c n f r a p i t s i a c o W i d ws no Tr y I o AP u t n a c n I F ci o
维普资讯
20 年 l 02 O月
电 脑 学 习
第5 期
给 V 应 用 程 序 制 作 托 盘 图 标 B
李 建 国
摘 要 介 绍 了 利 用 W id w AP no s I函 数 给 VB 应 用 程 序 制 作 托 盘 图 标 的 方 法
一
个 , 别 代 表 添 加 、 除 、 改 托 盘 上 的 图 标 。参 数 lD t 分 删 修 p aa N T F I O A A 类 型 的 参 数 非 常 重 要 , 其 中 cSz O I Y C ND T bi e
13操 作 说 明 . 调用 h l N tyc n 函数 可 以完成 系统 托 盘 区的所 有 S e _ oi lo l f 操 作 。 该 函 数 的参 数 有 d Mesg w sae和 lD t p aa两 个 。 参 数
d Mesg w sae是 N M— D、 I D L T 、 I MO I Y 中 的 I AD N M— E E E N M_ D F
如何用VISUAL BASIC编写托盘程序
ScI oi I n的函数声明 h lN tyc - f o
作者越舟t李夭明 (96),男 .甘肃甘谷人,夭求市委党校讲师 I6. 3 9
维普资讯
D cae F n t n S el t Io i e lr u ci h lNo c n Lb” S el2dl Al s “ o - h l .l” 3 i a
中田分类号:T 33 P 9 文献标 识码:B 文章 编号: 17-3 12 0 )2 0 90 3 115 (0 20 - 3 -3 0
l托盘程序 的慨 念及在VB中编写 的原 则
在Wid w 桌面上的任务栏里,右下角有 许多应用程序 no s 目标 ,如 系统时钟 、输 入法 、计 划任务等 。而 程序本身 的 窗 口是 隐藏的 ,若你 要调用应用 程序 的窗 口,则双击 该 图 标 即可 ,这种程序称为托 盘程序 。
c Sz Dn b ieAsL g h dA L wn s D唱
u D A Lo g l s n
u lg s L Fa sA Dr
u l a k  ̄ sg Cal c M b a eAs o g L n
H dA L n wu s o g’接受托盘 图标消息的窗口指针 uDAs o g’由程序定 义的图标识别符 。因为有的程 l n L 序有多个图标 u g s m ’对 托盘 图标操作 的标志,包括添加 、 Ras A 修改,删除 u al cMc g As og’标志应 用程序 的消息 C l ak  ̄ c L n b hcnA L n Io s o g’托盘 图标指针 sTpA  ̄n *4’当 鼠标 指到托盘 图标时提 示字符 z i s ' g6 Si
托盘程序详解
mnuTrayMaximize.Enabled = True
mnuTrayMinimize.Enabled = False
mnuTrayMove.Enabled = False
'【说明】
' 在窗口结构中为指定的窗口设置信息
'【返回值】
' Long,指定数据的前一个值
'【参数表】
End Sub
'保证在程序退出时删除托盘图标
Private Sub Form_Unload(Cancel As Integer)
RemoveFromTray
End Sub
'“文件”菜单的“退出”项被点击时
Private Sub mnuFileExit_Click()
Unload Me
'表示发送的是系统命令
Private Const WM_SYSCOMMAND = &H112
Private Const SC_MOVE = &HF010&
Private Const SC_RESTORE = &HF120&
Private Const SC_SIZE = &HF000&
'当主窗体加载时
托盘程序详解(一)
很多软件运行时会在系统托盘区(就是桌面右下角显示时间的区域)出现一个小图标,它作为程序运行的一个标志,我们可以通过使用小图标所弹出的菜单来控制应用程序的状态。本例就给出了一个功能比较完整的托盘程序,我们可以看到怎样用API函数Shell_NotifyIcon来添加、删除、更改托盘图标;而且例中还演示了为托盘图标添加右键菜单和浮动提示的方法。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
【转载】VB托盘程序详解2007/11/25 20:531、新建立一个VB6工程,将Form1的ShowInTaskBar属性设置为False2、菜单:工程--添加模块按“打开”这样就添加了一个新模块,名为Module1,保存为Module1.bas3、在Module1中写下如下代码:Option ExplicitPublic Const MAX_TOOLTIP As Integer = 64Public Const NIF_ICON = &H2Public Const NIF_MESSAGE = &H1Public Const NIF_TIP = &H4Public Const NIM_ADD = &H0Public Const NIM_DELETE = &H2Public Const WM_MOUSEMOVE = &H200Public Const WM_LBUTTONDOWN = &H201Public Const WM_LBUTTONUP = &H202Public Const WM_LBUTTONDBLCLK = &H203Public Const WM_RBUTTONDOWN = &H204Public Const WM_RBUTTONUP = &H205Public Const WM_RBUTTONDBLCLK = &H206Public Const SW_RESTORE = 9Public Const SW_HIDE = 0Public nfIconData As NOTIFYICONDATAPublic Type NOTIFYICONDATAcbSize As LonghWnd As LonguID As LonguFlags As LonguCallbackMessage As LonghIcon As LongszTip As String * MAX_TOOLTIPEnd TypePublic Declare Function ShowWindow Lib "user32" (ByVal hWnd As Long, ByVal nCmdShow As Long) As LongPublic Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long4、在Form1的Load事件中写下如下代码:Private Sub Form_Load()'以下把程序放入System Tray====================================System Tray BeginWith nfIconData.hWnd = Me.hWnd.uID = Me.Icon.uFlags = NIF_ICON Or NIF_MESSAGE Or NIF_TIP.uCallbackMessage = WM_MOUSEMOVE.hIcon = Me.Icon.Handle'定义鼠标移动到托盘上时显示的Tip.szTip = App.Title + "(版本 " & App.Major & "." & App.Minor & "." & App.Revision & ")" & vbNullChar.cbSize = Len(nfIconData)End WithCall Shell_NotifyIcon(NIM_ADD, nfIconData)'=============================================================System Tray EndMe.HideEnd Sub5、在Form1的QueryUnload事件中写入如下代码:Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer) Call Shell_NotifyIcon(NIM_DELETE, nfIconData)End Sub6、在Form1的MouseMove事件中写下如下代码:Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)Dim lMsg As SinglelMsg = X / Screen.TwipsPerPixelXSelect Case lMsgCase WM_LBUTTONUP'MsgBox "请用鼠标右键点击图标!", vbInformation, "实时播音专家"'单击左键,显示窗体ShowWindow Me.hWnd, SW_RESTORE'下面两句的目的是把窗口显示在窗口最顶层'Me.Show'Me.SetFocus'' Case WM_RBUTTONUP'' PopupMenu MenuTray '如果是在系统Tray图标上点右键,则弹出菜单MenuTray'' Case WM_MOUSEMOVE'' Case WM_LBUTTONDOWN'' Case WM_LBUTTONDBLCLK'' Case WM_RBUTTONDOWN'' Case WM_RBUTTONDBLCLK'' Case ElseEnd SelectEnd Sub7、现在将程序保存起来运行看看系统托盘处是否增加了一个本工程的图标。
单击此图标,Form1就自动弹出来了。
很多软件运行时会在系统托盘区(就是桌面右下角显示时间的区域)出现一个小图标,它作为程序运行的一个标志,我们可以通过使用小图标所弹出的菜单来控制应用程序的状态。
本例就给出了一个功能比较完整的托盘程序,我们可以看到怎样用API函数Shell_NotifyIcon来添加、删除、更改托盘图标;而且例中还演示了为托盘图标添加右键菜单和浮动提示的方法。
程序(附后)用到了Shell_NotifyIcon、SendMessage、CallWindowProc、SetWindowLong等API函数,其中Shell_NotifyIcon是主要的函数,它用来添加、删除、更改系统托盘区(taskbar status area)的图标,所以我们先来看看这个函数的声明和参数:使用API函数之前必须先在程序中声明如下:Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias"Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long其中各参数的意义如下表:参数:意义dwMessage 为消息设置值,它可以是以下的几个常数值:0、1、2NIM_ADD = 0 加入图标到系统状态栏中NIM_MODIFY = 1 修改系统状态栏中的图标NIM_DELETE = 2 删除系统状态栏中的图标LpData 用以传入NOTIFYICONDATA数据结构变量,其结构如下所示:Type NOTIFYICONDATAcbSize As Long 需填入NOTIFYICONDATA数据结构的长度HWnd As Long 设置成窗口的句柄Uid As Long 为图标所设置的ID值UFlags As Long 设置uCallbackMessage,hIcon,szTip是否有效UCallbackMessage As Long 消息编号HIcon As Long 显示在状态栏上的图标SzTip As String * 64 提示信息End Type返回值 Long,非零表示成功,零表示失败在使用这个API函数之前我们应该先定义结构类型NOTIFYICONDATA:Public Type NOTIFYICONDATAcbSize As Long HWnd As LongUid As Long UFlags As LongUCallbackMessage As LongHIcon As LongSzTip As String * 64End Type然后定义一个NOTIFYICONDATA的变量TheData来记录设置托盘图标的数据Private TheData As NOTIFYICONDATA这时我们就可以使用这个函数来设置系统托盘图标了,具体方法如下:1、添加图标With TheData.Uid = 0.HWnd = frm.HWnd 注释:frm.HWnd是程序主窗体的句柄.cbSize = Len(TheData).HIcon = frm.Icon.Handle 注释:frm.Icon.Handle指向主窗体的图标.UFlags = NIF_ICON.UCallbackMessage = TRAY_CALLBACK注释:作用是允许返回消息,在下一节中会有详细解释。
.UFlags = .UFlags Or NIF_MESSAGE.cbSize = Len(TheData)End WithShell_NotifyIcon NIM_ADD, TheData注释:根据前面定义NIM_ADD,设置为“添加模式”,然后添加2、删去图标With TheData.UFlags = 0End WithShell_NotifyIcon NIM_DELETE, TheData注释:根据前面定义NIM_DELETE,设置为“删除模式”3、更改图标With TheData.HIcon = pic.Handle注释:pic是图片狂PictureBox,存放图标文件.UFlags = NIF_ICONEnd WithShell_NotifyIcon NIM_MODIFY, TheData注释:根据前面定义NIM_MODIFY,设置为“更改模式”4、为图标添加浮动提示信息With TheData.SzTip = tip & vbNullChar注释:tip是字符串string,存储提示信息.UFlags = NIF_TIP注释:指明要对浮动提示进行设置End WithShell_NotifyIcon NIM_MODIFY, TheData注释:根据前面定义NIM_MODIFY,设置为“修改模式”通过以上几段代码我们就能根据自己需要添加、删除、更改系统托盘图标,并能添加系统图标上的浮动提示信息。