How to check if two controls overlap in Windows Forms

I created a class that allows the user to drag panels onto forms. How can I ensure that the user does not put two panels on top of each other? If so, I would like to toggle / highlight one of the controls while they both overlap.

I tried to set this in the OnMouseDown event, but it didn’t quite work.

In addition, the number of panels in the form depends on the number of images to be displayed on the form. Each panel has an image panel inside the panel.

+8
c # winforms panel mouseevent
source share
2 answers

A much better approach is to use the Rectangle.Bounds.IntersectsWith method, which does the check for you and can create cleaner code. I personally don't know about any performance issues or benefits, one way or another, although I would venture to suggest that just sorting through the controls and checking them with this would be faster than creating lists and loops.

Picturebox pic = new Picturebox(); foreach(Control picturebox in Form1){ if (pic.Bounds.IntersectsWith(picturebox.Bounds)) { //We have a problem, Houston, because we just collided! } } 

Hope this helps, although you asked this question a while ago.

+7
source share

So, I was able to resolve this issue with the sgud clause.

The trick was to use the Rectangle.Intersect method inside the OnMouseUp event.

Here is the intuition I used behind her. (this may not be the best solution)

1) Create a list of all the controls inside my main panel.

2) Go through the controls and create a list of all the Rectangle Bounds for each control. you can get it by control.Bounds

3) Go to the Bounds list and cross it with the current active anchor of the element.
If the returned rectangle is the same height and width as the active control, then assign a change to the back color property.

I hope this helps anyone who has a similar problem.

+1
source share

All Articles