c# - GetChildAtPoint 方法返回错误的控件

标签 c# winforms cursor-position

我的表单层次结构是这样的:

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/

相关文章:

数据库助手类的 C# 设计模式

c# - BitConverter 异常,目标数组太小

c# - 更新 Windows 窗体中的 UI 对象

assembly - 如何使8086清屏然后将光标移动到换行符打印出下一个函数

swift - 将 ScrollView/Keyboard 移动到 UITextView 光标位置

C# 右键单击​​ RichTextBox 中的移动光标

c# - 单击 Datagridview 中的行标题时选择整行

c# - 为什么我的 ActionLink 不工作?

c# - 在视觉继承的情况下,事件处理的标准方法是什么?

c# - 在对象 C# 中查找值的最佳方法