ElektroStudios
ElektroStudios

Reputation: 20494

Proper way to restore a default contextmenu for an edit control?

I'm in a situation where I want to decide whether to disable or enable the default edit contextmenu of a subclassed TextBox control, I've written this:

Public Property DisableEditMenu As Boolean = False

''' <summary>
''' Raises the <see cref="E:System.Windows.Forms.Control.Enter"/> event.
''' </summary>
''' <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
Protected Overrides Sub OnEnter(e As EventArgs)

    If Me.DisableEditMenu AndAlso MyBase.ContextMenuStrip Is Nothing Then
        ' Disable Copy/Cut/Paste contextmenu by creating a new empty one.
        MyBase.ContextMenuStrip = New ContextMenuStrip

    ElseIf Not Me.DisableEditMenu Then
        ' Restore default edit contextmenu...

    End If

    MyBase.OnEnter(e)

End Sub

The problem is... how I can restore the default contextmenu?

I've thinked about to solve it in this way, and it works ok, but I'm not sure if I'm being efficient or I'm doing unnecesary things than what i really should do to restore the default menu:

...
ElseIf Not Me.DisableEditMenu Then
    ' Restore default edit contextmenu...
    Using tb As New TextBox
        MyBase.ContextMenuStrip = tb.ContextMenuStrip
    End Using
...

Because .Net Framework Class Library provides a reference for default values, such as default control colors (eg: TextBox.DefaultBackColor), then maybe a default edit contextmenu is contained/referred in some Type that I didn't discovered yet? or to restore it efficientlly is more hard than I imagine?

Upvotes: 0

Views: 287

Answers (1)

To "restore the default contextmenu", set the ContextMenuStrip property to null.

Me.ContextMenuStrip = Nothing

However, there's no need to set the ContextMenu to a new empty instance. All you have to do is to suppress the WM_CONTEXTMENU message. MSDN describes this message as:

Notifies a window that the user clicked the right mouse button (right-clicked) in the window.

Public Class UITextBox
    Inherits TextBox

    Public Property DisableEditMenu As Boolean

    Protected Overrides Sub WndProc(ByRef m As Message)
        If ((m.Msg = WM_CONTEXTMENU) AndAlso Me.DisableEditMenu) Then
            Exit Sub
        Else
            MyBase.WndProc(m)
        End If

    End Sub

    Private Const WM_CONTEXTMENU As Integer = 123

End Class

Upvotes: 1

Related Questions