我有一个自定义TabControl
,其中TabPages
与ContextMenu
绑定了它们。
我希望菜单仅在点击页面标题时显示。
我所做的是,当点击TabControl
时,我会检查以下条件:
private void MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == Mousebuttons.Right)
{
for (int i = 0; i < TabCount; ++i)
{
Rectangle r = GetTabRect(i);
if (r.Contains(e.Location) /* && it is the header that was clicked*/)
{
// Change slected index, get the page, create contextual menu
ContextMenu cm = new ContextMenu();
// Add several items to menu
page.ContextMenu = cm;
page.ContextMenu.Show(this, e.Location);
}
}
}
}
如果我将MouseUp
绑定到TabControl
,我会在整个ContextMenu
中获得TabPage
。如果我将其绑定到TabPage
,我只会在正文中获得ContextMenu
,而不是在标题中。
有没有办法让ContextMenu只显示在标题点击?
答案 0 :(得分:8)
只是不要将ContextMenu分配给任何东西......只需显示它:
public class MyTabControl : TabControl
{
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
for (int i = 0; i < TabCount; ++i)
{
Rectangle r = GetTabRect(i);
if (r.Contains(e.Location) /* && it is the header that was clicked*/)
{
// Change slected index, get the page, create contextual menu
ContextMenu cm = new ContextMenu();
// Add several items to menu
cm.MenuItems.Add("hello");
cm.MenuItems.Add("world!");
cm.Show(this, e.Location);
break;
}
}
}
base.OnMouseUp(e);
}
}
答案 1 :(得分:3)
而不是像Idle_Mind所说的那样覆盖,你也可以对mouseevent上的普通tabcontrol做同样的事情:
private void tabControl1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
for (int i = 0; i < tabControl1.TabCount; ++i)
{
Rectangle r = tabControl1.GetTabRect(i);
if (r.Contains(e.Location) /* && it is the header that was clicked*/)
{
// Change slected index, get the page, create contextual menu
ContextMenu cm = new ContextMenu();
// Add several items to menu
cm.MenuItems.Add("hello");
cm.MenuItems.Add("world!");
cm.Show(tabControl1, e.Location);
break;
}
}
}
}
它完全相同,但不会在工具箱中添加额外的控件:) 如果要在多个TabControl上使用它,也可以使它成为通用的。
private void showContextMenu_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
TabControl tabControl1 = sender as TabControl;
[...]