BLOG.CSHARPHELPER.COM: Use a message filter to make TextBox controls not display context menus in C#
Use a message filter to make TextBox controls not display context menus in C#
The example Make a TextBox control without a context menu in C# shows how to make a class that inherits from TextBox but that doesn't display a context menu. That works but is a bit heavy handed, requiring you to create a new control class.
This example shows another approach: installing a message filter to discard messages that would tell a TextBox to display its context menu.
A message filter is an object that implements the IMessageFilter interface. The following code shows the NoCtxMenuFilter class that the example uses to discard context menu messages.
// Class to filter out right mouse button down messages.
private class NoCtxMenuFilter : IMessageFilter
{
public List TargetHandles = new List();
// If the message is right mouse down and the
// handle is in the target list, return true
// to indicate that the message should be ignored.
public bool PreFilterMessage(ref Message m)
{
const long WM_RBUTTONDOWN = 0x204;
// If it's not a right mouse button down, return false.
if (m.Msg != WM_RBUTTONDOWN) return false;
// See if the handle is in the target list.
return TargetHandles.Contains(m.HWnd);
}
}
The class provides a public list of IntPtr to hold the window handles of the target controls that should not receive right mouse down messages.
The real work is done in the PreFilterMessage method required by the IMessageFilter interface. This code checks the message's Msg parameter to see what message it is. If the message is not a right mouse down, the method returns false to indicate that the message should not be filtered out and should be handled normally. If the message is a right mouse down, the code returns true to discard the message if the window that is receiving the message is in the target list. The result is that controls with handles in the target list don't receive the WM_RBUTTONDOWN message so they don't display context menus.
When the program starts, it uses the following code to install its message filter.
// Install the message filter.
private void Form1_Load(object sender, EventArgs e)
{
// Create the filter and add TextBoxes.
NoCtxMenuFilter filter = new NoCtxMenuFilter();
filter.TargetHandles.Add(textBox1.Handle);
filter.TargetHandles.Add(textBox2.Handle);
// Install the filter.
Application.AddMessageFilter(filter);
}
This code creates a new NoCtxMenuFilter object and adds the handles of the two TextBoxes textBox1 and textBox2 to the object's target list. It then calls Application.AddMessageFilter to install the message handler.
Comments