views:

28

answers:

2

Surely this has got to be easy; I'm just not having any luck with it.

How would I get the TabPage of a given TabControl whose tab contains a given Point? For example, if I'm handling the MouseUp event and I want to know which tab the mouse was over when it was released.

I tried GetChildAtPoint, but that seems to always return the first tab (unless I'm using it wrong).

+1  A: 

You could try using the overload of GetChildAtPoint with GetChildAtPointSkip - this Connect bug suggests it could work.

Stuart Dunkeld
Definitely a useful overload to know about, but I can't seem to figure out how to apply it here. The available flags for the `GetChildAtPointSkip` enum are `Invisible`, `Disabled`, and `Transparent`; but in fact, I don't actually want to "skip" *any* pages. I just want the actual tab at the given point. I think the MS rep who claimed the bug was fixed by this overload on Connect was either mistaken, or else referring to a slightly different bug.
Dan Tao
+3  A: 

Try this:

TabPage GetPageByPoint(TabControl tabControl, Point point)
{
    for (int i = 0; i < tabControl.TabPages.Count; i++)
    {
        TabPage page = tabControl.TabPages[i];
        if (tabControl.GetTabRect(i).Contains(point))
            return page;
    }
    return null;
}

Good luck!

Homam
Yup, that's the one.
Hans Passant
I did try this, with no luck! Man, I think the problem is that I'm working with a point on the *screen*, not in relation to the tab control's client area. Maybe I can do the translation really quick...
Dan Tao
You've mentioned that you're using [MouseUp] event, I've tried it, just pass [e.Location] to the method.
Homam
Aha! Just needed to add a little `TabControl.PointToClient` magic to translate the screen coordinates to a `Point` relative to the tab control's position. Nice, thanks!
Dan Tao
@Homam: Sorry, I shouldn't have said `MouseUp` (though I was using that originally); I ended up needing to deal with this on `DragDrop`, which supplies screen coordinates.
Dan Tao