Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close tab on winforms tab control with middle mouse button

Tags:

c#

winforms

Is there any easy (5 lines of code) way to do this?

like image 936
Mladen Mihajlovic Avatar asked Apr 13 '09 20:04

Mladen Mihajlovic


2 Answers

The shortest code to delete the tab the middle mouse button was clicked on is by using LINQ.

Make sure the event is wired up
this.tabControl1.MouseClick += tabControl1_MouseClick;
And for the handler itself
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());
  }
}
And if you are striving for least amount of lines, here it is in one line
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()); } };
like image 111
Samuel Avatar answered Sep 20 '22 14:09

Samuel


Solution without LINQ not so compact and beautiful, but also actual:

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);
    }
}
like image 43
alexey_detr Avatar answered Sep 17 '22 14:09

alexey_detr