我创建了一个派生自TableLayoutPanel
的控件。当我在WinForms设计器中拖放该控件时,右键单击它会显示TableLayoutPanel
的默认上下文菜单。
我需要在设计时禁用此控件的默认上下文菜单。我尝试覆盖ContextMenu
和ContextMenuStrip
,但它没有帮助。
方法1:覆盖ContextMenu
public class MyControl : TableLayoutPanel
{
public MyControl()
{
}
public override ContextMenu ContextMenu { get => new ContextMenu();}
public override ContextMenuStrip ContextMenuStrip { get => new ContextMenuStrip(); }
}
方法2:当用户右键点击MyControl时发送ESC键,这样上下文菜单就不会出现
public class MyDesignerForm
{
ISelectionService service = (ISelectionService)serviceContainer.GetService(typeof(ISelectionService));
Application.AddMessageFilter(new MyControl(),service);
}
internal class MyMsgFilter : IMessageFilter
{
const int WM_RBUTTONDOWN = 0x0204;
const int WM_KEYDOWN = 0x100;
const int WM_KEYUP = 0x101;
const int VK_ESCAPE = 0x1B;
Control m_control;
[DllImport("User32.dll")]
public static extern bool PostMessage(IntPtr hwnd, int uMsg, int wParam, int lParam);
ISelectionService service = null;
public MyMsgFilter(Control control,ISelectionService Service)
{
this.m_control = control;
service = Service;
}
private void SendEscape(IntPtr hwnd)
{
PostMessage(hwnd, WM_KEYDOWN, VK_ESCAPE, 0);
PostMessage(hwnd, WM_KEYUP, VK_ESCAPE, 0);
}
#region IMessageFilter Members
public bool PreFilterMessage(ref Message m)
{
long wParam, lParam;
bool result;
if(m.Msg==WM_RBUTTONDOWN)
{
SendEscape(m_control.Handle);
return true;
}
return false;
}
#endregion
}