Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two re-sizable panels having different width. on re-sizing if they get overlapped then i want to get only overlapped area. I tried following to detect overlapped panels, but not idea about how to get overlapped area(width).
C#
Rectangle sr = new Rectangle(panel1.Left, panel1.Top, panel1.Width, panel1.Height);
foreach (Control ctrl in this.Controls)
{
	if (ctrl is Panel && ctrl != panel1)
	{
		Rectangle r = new Rectangle(ctrl.Left, ctrl.Top, ctrl.Width, ctrl.Height);
		if (sr.IntersectsWith(r))
		{
			//here i want only the overlapped area(width) of ctrl.
		}
	}
}

if have any idea please share.
Posted
Updated 2-Dec-14 22:13pm
v2

Call the Rectangle.Intersect Method (Rectangle, Rectangle)[^] to get the intersection rectangle and then use its Width property.
 
Share this answer
 
Comments
SachinSutar 3-Dec-14 4:23am    
Thanks...
DamithSL 3-Dec-14 4:27am    
yes, 5+
CPallini 3-Dec-14 4:30am    
You are welcome.
C#
if (sr.IntersectsWith(r))
{
   Rectangle rectangle3 = Rectangle.Intersect(sr, r);
   //rectangle3 represents the intersection of two other Rectangle structures
}
 
Share this answer
 
Comments
SachinSutar 3-Dec-14 4:21am    
Thanks..
It works very well.
You can simplify your code:
C#
// requires LInq
using System.Linq

private void getIntersection(Panel targetPanel, Control containerToSearch)
{
    Rectangle targetBounds = targetPanel.Bounds;

    Rectangle testIntersect;

    foreach (Panel thePanel in containerToSearch.Controls.OfType<Panel>())
    {
        if (thePanel == targetPanel) continue;

        testIntersect = Rectangle.Intersect(targetBounds, thePanel.Bounds);
        
        if (testIntersect != Rectangle.Empty)
        {
            // for testing only
            Console.WriteLine("panel name: {0} \r\nintersection: {1}", thePanel.Name, testIntersect.ToString());

            // whatever else you need to do ...

            // stop when you find the first intersecting Panel
            break;
        }
    }
}</panel>
 
Share this answer
 
v2
Comments
BillWoodruff 18-Dec-14 23:35pm    
Typo fixed Dec. 19, 2014 bw

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900