是否有任何简单的(5行代码)方法可以做到这一点?
答案 0 :(得分:20)
删除单击鼠标中键的选项卡的最短代码是使用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<TabPage>()
.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<TabPage>().Where((t, i) => tabControl.GetTabRect(i).Contains(e.Location)).First()); } };
答案 1 :(得分:6)
没有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);
}
}
答案 2 :(得分:2)
没有足够的积分向所提供的解决方案发布评论,但它们都有相同的缺陷:删除的标签中的控件不会被释放。
此致
答案 3 :(得分:-1)
你可以这样做:
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]);
}
}
基本上,您只需在选项卡控件上单击鼠标,仅在单击中间按钮时删除页面。