How to check if two controls are overlapping in Windows Forms

泪湿孤枕 提交于 2020-01-02 02:01:11

问题


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.


回答1:


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.




回答2:


So I was able to solve this question with the help of sgud's suggestion.

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

Here is the intuition I used behind it. (it might not be the neatest solution)

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

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

3) Go through the list of Bounds and intersect it with the currently active element's bound.
If the returned rectangle has height and width the same as the active control then assign change the back color property.

I hope this helps to anyone else that have a similar problem



来源:https://stackoverflow.com/questions/13917537/how-to-check-if-two-controls-are-overlapping-in-windows-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!