使用鼠标中键关闭winforms选项卡控件上的选项卡

有没有简单的(5行代码)方法来做到这一点?

删除单击鼠标中键的选项卡的最短代码是使用LINQ。

确保事件已连线

this.tabControl1.MouseClick += tabControl1_MouseClick; 

对于处理程序本身

 private void tabControl1_MouseClick(object sender, MouseEventArgs e) { var tabControl = sender as TabControl; var tabs = tabControl.TabPages; if (e.Button == MouseButtons.Middle) { tabs.Remove(tabs.Cast() .Where((t, i) => tabControl.GetTabRect(i).Contains(e.Location)) .First()); } } 

如果你正在争取最少的线路,这里就是一行

 tabControl1.MouseClick += delegate(object sender, MouseEventArgs e) { var tabControl = sender as TabControl; var tabs = tabControl.TabPages; if (e.Button == MouseButtons.Middle) { tabs.Remove(tabs.Cast().Where((t, i) => tabControl.GetTabRect(i).Contains(e.Location)).First()); } }; 

没有LINQ的解决方案不那么紧凑和美观,而且实际:

 private void TabControlMainMouseDown(object sender, MouseEventArgs e) { var tabControl = sender as TabControl; TabPage tabPageCurrent = null; if (e.Button == MouseButtons.Middle) { for (var i = 0; i < tabControl.TabCount; i++) { if (!tabControl.GetTabRect(i).Contains(e.Location)) continue; tabPageCurrent = tabControl.TabPages[i]; break; } if (tabPageCurrent != null) tabControl.TabPages.Remove(tabPageCurrent); } } 

没有足够的分数来发布评论到提供的解决方案,但他们都有相同的缺陷:删除选项卡中的控件不会被释放。

问候

你可以这样做:

 private void tabControl1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Middle) { // choose tabpage to delete like below tabControl1.TabPages.Remove(tabControl1.TabPages[0]); } } 

基本上,您只需在选项卡控件上单击鼠标,仅在单击中间按钮时删除页面。