Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two controls are overlapping in Windows Forms

I have created a class that allows the user to drag panels on a forms. How can I ensure that the user does not place two panels on top of each other? If they do, I would like to shift/or highlight one of the control while they are both overlapped.

I tried setting this in OnMouseDown event but that didn't quite work.

Also, the number of panels on the form vary depending on the number of pictures the form needs to show. Each panel has a picturebox inside the panel.

like image 612
Varun Dave Avatar asked Dec 17 '12 15:12

Varun Dave


1 Answers

A much better approach is to use the Rectangle.Bounds.IntersectsWith method, which does the check for you and can produce cleaner code. I'm personally unaware of any performance issues or benefits, one way or the other, although I would venture a guess that simply looping over your controls and checking them with this would be faster than building lists and loops both.

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

I hope this helps, even though you asked this question some time ago.

like image 158
Codefun64 Avatar answered Oct 07 '22 12:10

Codefun64