我试图检查 Windows 窗体控件是否“接触”同一窗体中的另一个 Windows 窗体控件。
示例:表单中有两个按钮。假设这两个按钮可以在表单的边界内移动。如何检查两个按钮是否接触(或任何 System.Control 与此相关)?
如何检查?
您可以对照其他控件检查Bounds该控件并检查它们是否有任何相交。
// 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
}
}
Run Code Online (Sandbox Code Playgroud)
如果所有控件都可以移动并且您想查看它们何时相互接触,您可以使用以下代码:
foreach (Control c1 in Controls)
{
foreach (Control c2 in Controls)
{
if (!c2.Equals(c1)
&& c1.Bounds.IntersectsWith(c2.Bounds))
{
// c1 has touched c2
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2551 次 |
| 最近记录: |