7

我有一个习惯TabControl,我对他们TabPagesContextMenu约束力。

我希望菜单仅在单击页眉时显示。

我所做的是,当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);
            }
        }
    }
}

如果我绑定MouseUpTabControl,我会得到 ContextMenu整个 TabPage. 如果我将它绑定到 TabPage,我只会 ContextMenu在正文中而不是在标题中。

有没有办法让 ContextMenu 只显示在标题 Click 上?

4

2 回答 2

11

只是永远不要将 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);
    }

}
于 2013-06-04T17:55:03.097 回答
4

除了像 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;
                }
            }
        }
    }

它的功能完全相同,但不会在您的工具箱中添加额外的控件:) 如果您想在多个 TabControls 上使用它,也可以使其成为通用控件。

    private void showContextMenu_MouseClick(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            TabControl tabControl1 = sender as TabControl;
            [...]
于 2016-11-25T13:41:58.383 回答