在C#中如何获取窗体上某个位置的控件

5
这是与C#获取窗体上控件位置相反的问题。
给定表单中的一个点位置,如何找出用户在该位置看到的哪个控件?
我目前使用HelpRequested表单事件显示一个独立的帮助表单,如MSDN:MessageBox.Show方法所示。
在MSDN示例中,使用sender控件来确定帮助消息,但在我的情况下,sender始终是表单而不是控件。
我想使用HelpEventArgs.MousePos来获取表单内的特定控件。
3个回答

6

1
这是一个不错的开始,谢谢。GetChildAtPoint是“相对于控件客户区域的左上角”,而HelpEventArgs.MousePos给出了鼠标指针的屏幕坐标。因此,在递归搜索特定控件之前,我需要进行一些转换以获得可用点。 - Daniel Ballinger

2

1
这是修改后的代码摘录,使用Control.GetChildAtPoint和Control.PointToClient来递归搜索用户单击点处定义标记的控件。
private void Form1_HelpRequested(object sender, HelpEventArgs hlpevent)
{
    // Existing example code goes here.

    // Use the sender parameter to identify the context of the Help request.
    // The parameter must be cast to the Control type to get the Tag property.
    Control senderControl = sender as Control;

    //Recursively search below the sender control for the first control with a Tag defined to use as the help message.
    Control controlWithTag = senderControl;
    do
    {
        Point clientPoint = controlWithTag.PointToClient(hlpevent.MousePos);
        controlWithTag = controlWithTag.GetChildAtPoint(clientPoint);

    } while (controlWithTag != null && string.IsNullOrEmpty(controlWithTag.Tag as string));

    // Existing example code goes here.    
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接