1

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 :)

  • 1
    Usually a hit detection is done on `MouseDown` but the actual closing is done if the `MouseUp` is still in the close rectangle image area. My guess is the `tabControl.MouseDown += ...;` has been assigned multiple times by mistake. – Loathing Feb 06 '21 at 00:15
  • Oh, but my `MouseDown` event is linked to the `TabControl` through the Designer, not in code :) –  Feb 06 '21 at 00:17
  • But, even so, would it be more efficient to do as you say, and detect hits on `MouseDown` then close tab(s) on `MouseUp`? –  Feb 06 '21 at 00:18
  • Set a breakpoint in your `MouseDown` code and then look at the call stack to determine where the calls are coming from. – Loathing Feb 06 '21 at 00:21
  • 1
    @Loathing , *scratch that*, I found the problem: It was as you said, I was accidentally assigning `tabControl.MouseDown` more than once, (*I unknowingly called it inside of the* `Form_Load` *event*) thanks! If you post your comment as an answer, I'll gladly accept! –  Feb 06 '21 at 00:21

1 Answers1

2

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

Loathing
  • 5,109
  • 3
  • 24
  • 35