【问题标题】:C# Get the control at a certain position on a formC#获取窗体上某个位置的控件
【发布时间】:2011-06-14 03:52:13
【问题描述】:

这是C# Get a control's position on a form的反题。

给定表单中的 Point 位置,我如何找出在该位置对用户可见的控件?

我目前正在使用 HelpRequested 表单事件来显示单独的帮助表单,如 MSDN: MessageBox.Show Method 所示。

在 MSDN 示例中,事件 sender 控件用于确定帮助消息,但在我的情况下,sender 始终是表单而不是控件。

我想使用HelpEventArgs.MousePos 来获取表单中的特定控件。

【问题讨论】:

    标签: c# winforms controls


    【解决方案1】:

    你可以使用Control.GetChildAtPoint:

    var controlAtPoint = theForm.GetChildAtPoint(thePosition);
    

    【讨论】:

      【解决方案2】:

      您可以在表单上使用Control.GetChildAtPoint 方法。如果您需要深入几个级别,则可能必须递归地执行此操作。请同时查看this answer

      【讨论】:

      • 这是一个好的开始,谢谢。 GetChildAtPoint 是“相对于控件客户区的左上角”,而 HelpEventArgs.MousePos 给出了鼠标指针的屏幕坐标。因此,在递归搜索特定控件之前,我需要进行一些转换以获得可用点。
      【解决方案3】:

      这是在提取修改后的代码时使用 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.    
      }
      

      【讨论】:

        猜你喜欢
        • 2010-12-01
        • 2010-10-02
        • 2015-03-02
        • 1970-01-01
        • 2014-11-22
        • 2013-01-09
        • 1970-01-01
        • 2010-12-04
        相关资源
        最近更新 更多