不要在TabControl上设置contextMenuStrip属性.而是这样做.连接到tabControl的MouseClick事件,然后手动显示上下文菜单.只有在单击选项卡本身时才会触发,而不是实际页面.如果单击该页面,则tabControl不会收到Click事件,TabPage会执行.一些代码:
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); } }
上下文菜单的打开事件可用于解决这两个问题
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; }