是否可以检测面板中特定坐标是否存在控件 - c#

时间:2015-09-24 02:29:47

标签: c# winforms user-controls

我在winforms应用程序中有一个面板,我想知道是否可以查看坐标上是否有UserControl,例如x:200,y:200。

我不只想检测UserControls的左上角为x:200,y:200,还要检测UserControl,如果是,它是x:150,y:150,W:100,H :100

我给了它一个快速谷歌,但我找不到任何东西。

[编辑] 总结一下:

黑色面板中,我希望能够检测蓝色坐标处是否存在UserControl(以红色显示)如图2所示,不仅仅是图像1。

enter image description here Image 2

2 个答案:

答案 0 :(得分:2)

第1步:针对当前使用Visible == true的所有窗口(或控件)进行迭代:How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

步骤2:对于每个Control,使用c.ClientRectangle属性获取相对于其父级的边界框。

步骤3:使用c.RectangleToScreen(...)方法将边界框转换为屏幕坐标。

步骤4:使用Rectangle方法测试鼠标是否在r.Contains(Point pt)内。

答案 1 :(得分:2)

您可以使用Control.GetChildAtPoint Method (Point),例如:

Control parent = your_panel;
Point pt = your_point;
// Uncomment if your point is in screen coordinates
// pt = parent.PointToClient(pt);
Control child = parent.GetChildAtPoint(pt);
if (child != null)
{
    // There is some control, but it might not be the one you are searching for.

    // Uncomment if you are searching for a direct child of your panel
    // while (child.Parent != parent) child = child.Parent;

    // Use other criterias. For instance:
    var userControl = child as UserControl;
    if (userControl != null)
    {
        // There you go.
    }
}
相关问题