BLOG.CSHARPHELPER.COM: Make a TextBox control without a context menu in C#
Make a TextBox control without a context menu in C#
Normal TextBoxes have a context menu that appears when you right-click them (see the picture on the right), but what if you don't want that context menu? I mean, really. Do I need to have "Show Unicode control characters" and "Open IME" on every single TextBox? (If you don't know, "Open IME" toggles the Input Method Editor that lets you enter Chinese, Japanese, Korean, and other non-Latin characters from your keyboard. If you don't use those languages, you don't need it.)
You can replace a TextBox's context menu with one of your own by adding a ContextMenuStrip to the form and setting the TextBox's ContextMenuStrip property equal to to it, but there's no simple way to remove the ContextMenuStrip.
This example uses the following code to create a new NoCtxMnuTextBox class that is a TextBox without the context menu.
public class NoCtxMnuTextBox : TextBox
{
// Ignore WM_CONTEXTMENU messages.
protected override void WndProc(ref Message m)
{
const int WM_CONTEXTMENU = 0x7B;
if (m.Msg != WM_CONTEXTMENU) base.WndProc(ref m);
}
}
This control inherits from TextBox. Its only change is that it overrides its WndProc method to examine the events the control receives. The code passes all messages to the TextBox base class's WndProc method except for the WM_CONTEXTMENU message, which calls for the context menu to be displayed. The base class's WndProc handles all of the other messages normally.
The main program uses the following code to create a NoCtxMnuTextBox when its form loads.
private void Form1_Load(object sender, EventArgs e)
{
NoCtxMnuTextBox txt = new NoCtxMnuTextBox();
txt.Parent = this;
int gap = txtNewContextMenu.Top - txtNormal.Bottom;
txt.SetBounds(
txtNewContextMenu.Left,
txtNewContextMenu.Bottom + gap,
txtNewContextMenu.Width,
txtNewContextMenu.Height);
}
You can also add the control to the form at design time. To do that you need to first compile the control and add it to the Toolbox. (Because I never post compiled code, the example you download would not have the control compiled so you wouldn't be able to use it right away. Creating it in code just seemed easier.)
Comments