Suppress default Edit popup menu in TextBox controls with subclassing

When you right-click a TextBox control, Windows sends it a WM_CONTEXTMENU message, to which VB reacts by displaying the default Edit popup menu, that contains editing commands such as Cut, Copy, Paste, and Select All. Using a subclassing technique you can easily trap this message before it reaches the original window procedure, and suppress the default Edit menu or substitute it with a custom popup menu. Thanks to the MsgHook DLL this is a trivial task:

' REQUIRES THE MSGHOOK.DLL COMPONENT' you can omit the following constant definition, ' because it is contained in the MsgHook type libraryConst WM_CONTEXTMENU = &H7BDim WithEvents TextBoxHook As MsgHookPrivate Sub Form_Load()    ' subclass the Text1 control    Set TextBoxHook = New MsgHook    TextBoxHook.StartSubclass Text1.hWndEnd SubPrivate Sub TextBoxHook_BeforeMessage(uMsg As Long, wParam As Long, _    lParam As Long, retValue As Long, Cancel As Boolean)    If uMsg = WM_CONTEXTMENU Then        ' Show a custom popup menu.        PopupMenu mnuPopup        ' Cancel the default processing        ' (i.e. don't display the default context menu).        Cancel = True    End IfEnd Sub

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

More From DevX