Mladen Mihajlovic
Mladen Mihajlovic

Reputation: 6445

Close tab on winforms tab control with middle mouse button

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

Upvotes: 10

Views: 8145

Answers (4)

jimjim
jimjim

Reputation: 2503

Don't have enough points to post a comment to the provided solutions but they all suffer from the same flaw: The controls within the removed tab are not released.

Regards

Upvotes: 2

alexey_detr
alexey_detr

Reputation: 1700

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

Upvotes: 6

Samuel
Samuel

Reputation: 38356

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

Upvotes: 24

ryanulit
ryanulit

Reputation: 5001

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.

Upvotes: -1

Related Questions