检查控件是否“触摸"另一个控件 [英] Check if a control is "touching" another control

查看:27
本文介绍了检查控件是否“触摸"另一个控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查一个 Windows 窗体控件是否正在接触"同一窗体中的另一个 Windows 窗体控件.

I am trying to check if a Windows Forms control is "touching" another Windows Forms control within the same Form.

示例:表单中有两个按钮.假设这两个按钮可以在 Form 的边界内移动.如何检查两个按钮是否在触摸(或任何 System.Control 与此相关)?

Example: There are two buttons inside a Form. Lets say that the two buttons are moveable within the boundaries of the Form. How would one check if the two button are touching (or any System.Control for that matter)?

如何检查?

推荐答案

您可以对照其他控件检查控件 Bounds 并检查它们是否有任何交叉.

You can check the control Bounds against other controls and check if they have any intersct.

// if your first control is specified you can use the following code
foreach (Control c2 in Controls)
{
    if (!c2.Equals(c1) && c2 is Button /* if you want it to be just buttons */
    && c1.Bounds.IntersectsWith(c2.Bounds))
    {
        // c1 has touched c2
    }

}

如果所有控件都可以移动并且您想查看它们何时相互接触,您可以使用以下代码:

If all controls can move and you want to see when they touch each other you can use the code below:

foreach (Control c1 in Controls)
{
    foreach (Control c2 in Controls)
    {
        if (!c2.Equals(c1) 
        && c1.Bounds.IntersectsWith(c2.Bounds))
        {
            // c1 has touched c2
        }

    }
}

这篇关于检查控件是否“触摸"另一个控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆