Search code examples
c#winformstabcontrolclose-button

How do I stop the close button from closing more than one tab? C# TabControl with a Close Button


So, I followed a couple of tutorials on TabControl with a Close Button, and I came up with a solution- however, it seems that by pressing the close button, it also closes the next tab over and sometimes the next tab after that.

Here is the MouseDown code:

var CloseImage = Properties.Resources.Close;

        for (var i = 0; i < this.tabControl1.TabPages.Count; i++)
        {
            var tabRect = this.tabControl1.GetTabRect(i);
            tabRect.Inflate(Convert.ToInt32(-3.5), -2);
            var imageRect = new Rectangle(tabRect.Right - CloseImage.Width,
                                     tabRect.Top + (tabRect.Height - CloseImage.Height) / 2,
                                     CloseImage.Width,
                                     CloseImage.Height);
            if (imageRect.Contains(e.Location))
            {
                if (tabControl1.TabCount > 1)
                {
                    this.tabControl1.TabPages.RemoveAt(i);

                    return;
                }
            }
        }

The TabControl.DrawMode is OwnerDrawFixed

It draws just fine, (hence why I'm not posting the draw code.) but, there seems to be a problem with the MouseDown event that I can't seem to find myself..

Any idea why it's closing multiple tabs instead of just the one I wanted it to? Thanks :)


Solution

  • My guess is the tabControl.MouseDown += ...; has been assigned multiple times by mistake.