GetChildAtPoint method is returning the wrong control

非 Y 不嫁゛ 提交于 2019-12-10 19:14:23

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/7508943/getchildatpoint-method-is-returning-the-wrong-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!