说三道四技术文摘-感悟人生的经典句子
说三道四 > 文档快照

屏蔽TextBox的系统菜单 -VB资料

HTML文档下载 WORD文档下载 PDF文档下载
屏蔽TextBox的系统菜单 -VB资料
TextBox是最常用的控件之一,很多时候我们需要处理在其上的右键处理.而系统默认有右键菜单, 因此很多时候影响程序的美观.其实,我们可以将系统的右键菜单屏蔽掉.屏蔽TextBox右键菜单的 方法有很多,下面主要介绍常用的两种方法:

方法一:投机取巧法;
本方法实现起来十分简单,在某些场合下使用起来很方便;不足是有些场合下不适用.
>>步骤1----建立新工程,在窗体上放置一个TextBox;
>>步骤2----在窗体上创建一菜单,设其Name = a;Visible = false;
>>步骤3----编写如下代码:
Private Sub Text1_MouseDown(Button As Integer, Shift _
As Integer, X As Single, Y As Single)
If Button = vbRightButton Then
Text1.Enabled = False
Text1.Enabled = True
PopupMenu a
End If
End Sub

>>步骤4----编译运行,在TextBox中按下鼠标右键,看看,系统菜单不见了,弹出的只是你自己定义的菜单. 简单吧!


方法二:截获系统消息法.
本方法实现起来相对来说,麻烦些,不过,应该说这种方法放之四海而皆适用.
首先取得系统函数的地址,并保存,然后用自定义的函数代替系统函数,最后恢复系统函数,弹出自定义菜单.
请看下面的代码:
>>步骤1----建立新工程,在窗体上放置一个TextBox; >>步骤2----在窗体上创建一菜单;设其Name = a;Visible = false;
>>步骤3----添加以模块,加入如下代码:

Public OldWinProc As Long' 保存系统窗口函数的地址
Public Const WM_CONTEXTMENU = &H7B' 当右击文本框时,
系统发送这条消息

Public Declare Function GetWindowLong Lib "user32" Alias _
"GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) _
As Long
Public Declare Function SetWindowLong Lib "user32" Alias _
"SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, _
ByVal dwNewLong As Long) As Long
Private 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 Function SubClass_WndMessage(ByVal hWnd As _
OLE_HANDLE,ByVal Msg As OLE_HANDLE, ByVal wParam As OLE_HANDLE, _
ByVal lParam As Long) As Long
If Msg <> WM_CONTEXTMENU Then
SubClass_WndMessage = CallWindowProc(OldWinProc, _
hWnd, Msg,wParam, lParam)
' 如果消息不是WM_CONTEXTMENU,就调用系统的窗口处理函数
Exit Function
End If
SubClass_WndMessage = True
End Function

>>步骤4----在窗体中加入如下代码:
Private Const GWL_WNDPROC = (-4)

Private Sub Text1_MouseDown(Button As Integer, Shift As _
Integer, X As Single, Y As Single)

If Button = 1 Then Exit Sub
OldWinProc = GetWindowLong(Text1.hWnd, GWL_WNDPROC)
' 取得窗口函数的地址
Call SetWindowLong(Text1.hWnd, GWL_WNDPROC, AddressOf _
SubClass_WndMessage)
' 用SubClass_WndMessage代替窗口函数处理消息
End Sub

Private Sub Text1_MouseUp(Button As Integer, Shift _
As Integer, X As Single, Y As Single)
If Button = 1 Then Exit Sub
Call SetWindowLong(Text1.hWnd, GWL_WNDPROC, OldWinProc)
' 恢复窗口的默认函数
PopupMenu a
' 弹出自定义菜单
End Sub

>>步骤5----编译运行,系统菜单不见了,弹出自定义菜单.
备案号:鲁ICP备13029499号-2 说三道四 www.s3d4.cn 说三道四技术文摘