我的表单层次结构是这样的:
Form -> TableLayoutOne -> TableLayoutTwo -> Panel -> ListBox
在 ListBox 的 MouseMove 事件中,我有这样的代码:
Point cursosPosition2 = PointToClient(new Point(Cursor.Position.X, Cursor.Position.Y));
Control crp = this.GetChildAtPoint(cursosPosition2);
if (crp != null)
MessageBox.Show(crp.Name);
MessageBox 显示“TableLayoutOne”,但我希望它显示“ListBox”。我的代码哪里出错了?谢谢。
最佳答案
GetChildFromPoint()
方法使用 native ChildWindowFromPointEx()
方法,其文档说明:
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.
注意粗体文本:该方法不能得到你想要的。
理论上,您可以在返回的控件上调用 GetChildFromPoint()
,直到得到 null
:
Control crp = this.GetChildAtPoint(cursosPosition2);
Control lastCrp = crp;
while (crp != null)
{
lastCrp = crp;
crp = crp.GetChildAtPoint(cursorPosition2);
}
然后您就会知道 lastCrp
是该位置的最低后代。
关于c# - GetChildAtPoint 方法返回错误的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7508943/