Reputation: 97
I am trying to check if a Windows Forms control is "touching" another Windows Forms control within the same Form.
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)?
How can this be checked?
Upvotes: 2
Views: 2641
Reputation: 9658
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
}
}
}
Upvotes: 5
Reputation: 5610
Maintain display rectangle of all parent controls. For example if there is a group box maintain display rectangle of that and not of controls inside it. While moving a control, check if current display rectangle overlaps with another.
Upvotes: 0