这是与C# Get a control's position on a form相反的问题。
给定表单中的Point位置,如何找出该位置的用户可以看到哪个控件?
我目前正在使用HelpRequested表单事件来显示单独的帮助表单,如MSDN: MessageBox.Show Method所示。
在MSDN示例中,事件sender
控件用于确定帮助消息,但在我的情况下,sender
始终是表单而不是控件。
我想使用HelpEventArgs.MousePos来获取表单中的特定控件。
答案 0 :(得分:5)
您可以在表单上使用Control.GetChildAtPoint方法。如果你需要深入几个级别,你可能必须递归地执行此操作。另请参阅this answer。
答案 1 :(得分:2)
您可以使用Control.GetChildAtPoint:
var controlAtPoint = theForm.GetChildAtPoint(thePosition);
答案 2 :(得分:1)
这是使用Control.GetChildAtPoint和Control.PointToClient提取修改后的代码,以递归方式搜索控件,并在用户单击的位置定义Tag。
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.
}