VBGood网站全文搜索 Google

搜索VBGood全站网页(全文搜索)
首页 - 经验之谈 - 隐藏文本框控件的环境菜单(又一方法)
发表评论(0)作者:, 平台:, 阅读:10276, 日期:2000-03-12
隐藏文本框控件的环境菜单



如果一个窗体中有一个文本框控件,当你用鼠标右键单击它时,会弹出一个环境菜

单,里面有诸如:拷贝、撤销、粘贴之类的选项。有时这个菜单会妨碍你的应用程

序界面的一致性,或者你想让用户在用鼠标右键单击文本框时,弹出你自已事先设

计好的菜单。


首先添加一个标准模块,在标准模块中写入如下代码:


Option Explicit


Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA

" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As

Long

Public 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


Public Const GWL_WNDPROC = (-4)

Public Const WM_CONTEXTMENU = &H7B

Global lpPrevWndProc As Long

Global gHW As Long


Public Sub Hook()

lpPrevWndProc = SetWindowLong(gHW, GWL_WNDPROC, AddressOf gWindowProc)

End Sub


Public Sub Unhook()

Dim temp As Long

temp = SetWindowLong(gHW, GWL_WNDPROC, lpPrevWndProc)

End Sub


Public Function gWindowProc(ByVal hWnd As Long, ByVal Msg As Long, ByVal

wParam As Long, ByVal lParam As Long) As Long

If Msg = WM_CONTEXTMENU

Then Debug.Print "截获 WM_CONTEXTMENU于 " & Now

gWindowProc = True

Else ' 传递其他所有消息到默认的消息句柄

gWindowProc = CallWindowProc(lpPrevWndProc, hWnd, Msg, wParam, lParam)

End If

End Function


在窗体中加入两个文本框控件。然后制作一个名为mnuTempMenu的菜单,其中有两

个菜单项,分别为Option1和Option2


将下面的代码放在相应的事件中。


Private Sub Form_Load()

Dim Ctrl As Control

For Each Ctrl In Me.Controls

If TypeOf Ctrl Is TextBox Then

gHW = Ctrl.hWnd

Hook

End If

Next

End Sub


Private Sub Form_Unload(Cancel As Integer)

Unhook

End Sub


Private Sub Text1_MouseDown(Button As Integer, Shift As Integer, X As

Single, Y As Single)

If Button = 2 Then Me.PopupMenu mnuTempMenu

End If

End Sub


按F5运行程序后,用鼠标分别右击两个文本框,你会发现Text1文本框会弹出你自

定义的菜单,而Text2则没有反应。