Search code examples
c#winformscursor-position

GetChildAtPoint method is returning the wrong control


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.


Solution

  • 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.