Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabControl Context Menu

In a Windows Forms app I set the ContextMenuStrip property on a TabControl.

  1. How can I tell the user clicked a tab other then the one that is currently selected?
  2. How can I restrict the context menu from showing only when the top Tab portion with the label is clicked, and not elsewhere in the tab?
like image 747
blu Avatar asked Jan 19 '09 14:01

blu


2 Answers

Opening event of context menu can be used to solve both problems

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{            
    Point p = this.tabControl1.PointToClient(Cursor.Position);
    for (int i = 0; i < this.tabControl1.TabCount; i++)
    {
        Rectangle r = this.tabControl1.GetTabRect(i);
        if (r.Contains(p))
        {
            this.tabControl1.SelectedIndex = i; // i is the index of tab under cursor
            return;
        }
    }
    e.Cancel = true;
}
like image 100
nisar Avatar answered Oct 11 '22 23:10

nisar


Don't bother setting the contextMenuStrip property on the TabControl. Rather do it this way. Hook up to the tabControl's MouseClick event, and then manually show the context menu. This will only fire if the tab itself on top is clicked on, not the actual page. If you click on the page, then the tabControl doesn't receive the click event, the TabPage does. Some code:

public Form1()
{
    InitializeComponent();
    this.tabControl1.MouseClick += new MouseEventHandler(tabControl1_MouseClick);
}

private void tabControl1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        this.contextMenuStrip1.Show(this.tabControl1, e.Location);
    }


}
like image 31
BFree Avatar answered Oct 11 '22 23:10

BFree