本文主要是介绍动态建立弹出式菜单技术及其应用示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
建立一个标准EXE新工程,在窗体上添加一个Listbox和一个Text控件。
然后在窗体中粘贴下面代码:(窗体代码)
Option Explicit
Private Sub Form_Load()
List1.AddItem "使用鼠标右键单击这里"
End Sub
Private Sub List1_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single)
Dim cMenu As cPopupMenu
Dim ret As Long
If Button = vbRightButton Then
Set cMenu = New cPopupMenu
ret = cMenu.Popup("撤销", "-", "剪切", "复制", "粘贴", "删除")
Text1.Text = ret
End If
End Sub
然后在工程中添加一个新类,名称为:cPopupMenu
然后在类cPopupMenu的代码窗体中粘贴如下代码:
Option Explicit
Private Type POINT
x As Long
y As Long
End Type
Private Const MF_ENABLED = &H0&
Private Const MF_DISABLED = &H2&
Private Const MF_SEPARATOR = &H800&
Private Const MF_STRING = &H0&
Private Const TPM_RIGHTBUTTON = &H2&
Private Const TPM_LEFTALIGN = &H0&
Private Const TPM_NONOTIFY = &H80&
Private Const TPM_RETURNCMD = &H100&
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINT) As Long
Private Declare Function GetForegroundWindow Lib "user32" () As Long
Private Declare Function CreatePopupMenu Lib "user32" () As Long
Private Declare Function AppendMenu Lib "user32" Alias "AppendMenuA" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long, ByVal sCaption As String) As Long
Private 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, nIgnored As Long) As Long
Private Declare Function DestroyMenu Lib "user32" (ByVal hMenu As Long) As Long
Public Function Popup(ParamArray param()) As Long
Dim iMenu As Long
Dim hMenu As Long
Dim nMenus As Long
Dim p As POINT
GetCursorPos p '得到当前光标位置
hMenu = CreatePopupMenu() '创建一个空的弹出式菜单
nMenus = 1 + UBound(param) '得到菜单数目
For iMenu = 1 To nMenus
If Trim$(CStr(param(iMenu - 1))) = "-" Then '画分隔符号
AppendMenu hMenu, MF_SEPARATOR, iMenu, ""
Else
AppendMenu hMenu, MF_STRING + MF_ENABLED, iMenu, CStr(param(iMenu - 1))
End If
Next iMenu
'TrackPopupMenu 函数返回用户选择的菜单项目或者取消选择
iMenu = TrackPopupMenu(hMenu, TPM_RIGHTBUTTON + TPM_LEFTALIGN + TPM_NONOTIFY + TPM_RETURNCMD, p.x, p.y, 0, GetForegroundWindow(), 0)
DestroyMenu hMenu '释放hMenu
Popup = iMenu '返回选择的菜单索引号,取消选择时候返回0
End Function
然后保存工程,按F5运行,用鼠标点击看看,是不是有菜单出现了?
---by 唐细刚 2004-7-9
这篇关于动态建立弹出式菜单技术及其应用示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!