GetChildAtPoint method is returning the wrong control
Asked Answered
C

2

5

My form hierarchy is something like this:

Form -> TableLayoutOne -> TableLayoutTwo -> Panel -> ListBox

In the MouseMove event of the ListBox, I have code like this:

    Point cursosPosition2 = PointToClient(new Point(Cursor.Position.X, Cursor.Position.Y));
    Control crp = this.GetChildAtPoint(cursosPosition2);
    if (crp != null)
        MessageBox.Show(crp.Name);

The MessageBox is showing me "TableLayoutOne", but I expect it to show me "ListBox". Where in my code am I going wrong? Thanks.

Castaway answered 22/9, 2011 at 2:35 Comment(0)
P
10

The GetChildFromPoint() method uses the native ChildWindowFromPointEx() method, whose documentation states:

Determines which, if any, of the child windows belonging to the specified parent window contains the specified point. The function can ignore invisible, disabled, and transparent child windows. The search is restricted to immediate child windows. Grandchildren and deeper descendants are not searched.

Note the bolded text: the method can't get what you want.

In theory you could call GetChildFromPoint() on the returned control until you got null:

Control crp = this.GetChildAtPoint(cursosPosition2);
Control lastCrp = crp;

while (crp != null)
{
    lastCrp = crp;
    crp = crp.GetChildAtPoint(cursorPosition2);
}

And then you'd know that lastCrp was the lowest descendant at that position.

Potted answered 22/9, 2011 at 2:52 Comment(4)
Dang! Thanks for info...do you have other thoughts on how to get it? maybe reading Cursor location and checking if it is inside the location of ListBox?Castaway
See my update; you can keep calling GetChildAtPoint() on the returned control to go deeper in the hierarchy. You're free to check the type of control at each stage, too, so you could bail out if you found what you were looking for.Potted
the crp = crp.GetChildAtPoint(cursorPosition2) is written twice which is not so beautiful, also Invisible controls are not excluded. see my postCrape
Better integrate the next answer that uses GetChildAtPointSkip.Invisible | GetChildAtPointSkip.TransparentDoeskin
C
4

a better code can be written as following:

Public Control FindControlAtScreenPosition(Form form, Point p)
{
    if (!form.Bounds.Contains(p)) return null; //not inside the form
    Control c = form, c1 = null;
    while (c != null)
    {
        c1 = c;
        c = c.GetChildAtPoint(c.PointToClient(p), GetChildAtPointSkip.Invisible | GetChildAtPointSkip.Transparent); //,GetChildAtPointSkip.Invisible
    }
    return c1;
}

The usage is as here:

Control c = FindControlAtScreenPosition(this, Cursor.Position);
Crape answered 26/9, 2018 at 5:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.