开发者

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.


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜