tags:

views:

1404

answers:

3

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

A: 

You could do this:

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

Basically you are just catching a mouse click on tab control and only deleting a page if the middle button was clicked.

ryanulit
This won't close the tab that was clicked on. This would drive me insane if it deleted the first one no matter which one I clicked.
Samuel
Well you would change it to select whatever tab you wanted to get rid off.
ryanulit
+10  A: 

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()); } };
Samuel
That's just beautiful code...
Mladen Mihajlovic
Now you're just showing off :) Brilliant man, thanks.
Mladen Mihajlovic
+3  A: 

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