编程语言
首页 > 编程语言> > c# – 确定打开了哪个标签页

c# – 确定打开了哪个标签页

作者:互联网

我正在尝试获取鼠标右键单击的标签页,换句话说是打开contextmenustrip的标签页.

有一个名为Close的toolstripmenuitem,我用它来关闭点击的标签.

我用过这段代码:

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 onm ouseClick(MouseEventArgs e)
    {
        base.OnMouseClick(e);
        if (e.Button == MouseButtons.Right)
            lastpoint = Cursor.Position;

    }

我还添加了(添加标签页时):

    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;
    }

问题是最后一个点总是(0,0)!!
为什么?
欢迎任何其他建议的想法
提前

解决方法:

这些事件处理程序都不会实际运行.不是表单的OnMouseClick()方法,因为您实际上没有右键单击表单.而不是标签页的MouseClick事件处理程序,因为您给TabControl一个上下文菜单.所以最后一点是空的是预期的结果.

目前尚不清楚您希望此上下文菜单如何工作.如果您通过右键单击选项卡页面来使用它,那么它很简单,只需销毁所选页面:

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

如果通过右键单击未选中的选项卡来激活它,则会变得更复杂.您必须记住单击了哪个选项卡,使用上下文菜单的Opening事件来执行此操作:

    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();
    }

标签:c,click,tabpage,contextmenustrip
来源: https://codeday.me/bug/20190624/1279953.html