Search code examples
c#clicktabpagecontextmenustrip

Determining which tabpage has opened


I'm trying to get the tabpage that was clicked by right button of mouse,in another words the tabpage that opened the contextmenustrip.

There's a toolstripmenuitem called Close which I used to close the tab that was clicked on.

I used this code :

public partial class USBrowser : Form

    {
        private Point lastpoint;
    }


private void closeTabToolStripMenuItem_Click(object sender, EventArgs e)
{
    for (int i = 0; i < browserTabControl.TabCount; i++)
    {
        Rectangle rec = browserTabControl.GetTabRect(i);
        if (rec.Contains(this.PointToClient(lastpoint)))
           closeTab(i);//this function closes the tab at specific index                
    }
}

    protected override void OnMouseClick(MouseEventArgs e)
    {
        base.OnMouseClick(e);
        if (e.Button == MouseButtons.Right)
            lastpoint = Cursor.Position;

    }

I also added(when adding the tabpage) :

    browserTabControl.TabPages.Insert(browserTabControl.TabCount - 1,WebPage);
    browserTabControl.SelectTab(WebPage);
    browserTabControl.SelectedTab.MouseClick += SelectedTab_MouseClick;

    void SelectedTab_MouseClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
            lastpoint = Cursor.Position;
    }

The problem is that the lastpoint is always (0,0) !! Why ? Any other suggested idea is welcomed thanx in advance


Solution

  • None of these event handlers will actually run. Not the form's OnMouseClick() method since you are not actually right-clicking the form. And not the tab page's MouseClick event handler since you gave the TabControl a context menu. So lastpoint being empty is the expected outcome.

    It is not clear how you want this context menu to work. If you use it by right-clicking the tab page then it is simple, just destroy the selected page:

        private void closeToolStripMenuItem_Click(object sender, EventArgs e) {
            tabControl1.SelectedTab.Dispose();
        }
    

    If you activate it by right-clicking a tab, one that isn't selected, then it gets more complicated. You have to memorize which tab was clicked on, do so by using the context menu's Opening event:

        private TabPage RightClickedTab;
    
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) {
            RightClickedTab = tabControl1.SelectedTab;
            var pos = tabControl1.PointToClient(Cursor.Position);
            for (int tab = 0; tab < tabControl1.TabCount; ++tab) {
                if (tabControl1.GetTabRect(tab).Contains(pos)) {
                    RightClickedTab = tabControl1.TabPages[tab];
                    break;
                }
            }
        }
    
        private void closeToolStripMenuItem_Click(object sender, EventArgs e) {
            if (RightClickedTab != null) RightClickedTab.Dispose();
        }