Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleRemove several TextBox context menus
Description
Keywordscontext menu, popup menu, TextBox
CategoriesAPI, Controls
 
My book Custom Controls Library disables context menus to implement several custom controls.

Warning: Subclassing is dangerous. The debugger does not work well when a new WindowProc is installed. If you halt the program instead of unloading its forms, it will crash and so will the Visual Basic IDE. Save your work often! Don't say you weren't warned.

When the form loads, the program calls RemoveContextMenu for three TextBoxes. RemoveContextMenu subclasses a TextBox and saves the address of its original WindowProc in the m_OldWindowProcs collection.

 
Public m_OldWindowProcs As Collection

' Subclass to remove this TextBox's context menu.
Public Sub RemoveContextMenu(ByVal txt As TextBox)
    ' Initialize the collection.
    If m_OldWindowProcs Is Nothing Then Set _
        m_OldWindowProcs = New Collection

    ' Subclass, saving the old WindowProc's
    ' address using the hWnd as a key.
    m_OldWindowProcs.Add _
        SetWindowLong( _
            txt.hWnd, GWL_WNDPROC, _
            AddressOf NewWindowProc), _
        "=" & Format$(txt.hWnd)
End Sub
 
The new WindowProc finds a TextBox's hWnd in the m_OldWindowProcs collection. It checks for destruction and then passes all messages except WM_CONTEXTMENU on to the original WindowProc.
 
' Pass along all messages except the one that
' makes the context menu appear.
Public Function NewWindowProc(ByVal hWnd As Long, ByVal msg _
    As Long, ByVal wParam As Long, ByVal lParam As Long) As _
    Long
Const WM_NCDESTROY = &H82
Dim old_window_proc As Long

    ' Get the TextBox's original WindowProc.
    old_window_proc = m_OldWindowProcs("=" & Format$(hWnd))

    ' See if the TextBox is being destroyed.
    If msg = WM_NCDESTROY Then
        ' Restore the original WindowProc.
        SetWindowLong _
            hWnd, GWL_WNDPROC, _
            old_window_proc

        ' Remove this entry from the collection.
        m_OldWindowProcs.Remove "=" & Format$(hWnd)
    End If

    ' Pass messages other than WM_CONTEXTMENU
    ' the the original WindowProc.
    If msg <> WM_CONTEXTMENU Then _
        NewWindowProc = CallWindowProc( _
            old_window_proc, hWnd, msg, _
            wParam, lParam)
End Function
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated