How-To: Find a bounding rectangle of WinForms Controls
Thursday, August 21st, 2008Recently I was refactoring a peace of code which calculates a bounding rectangle of a controls on a form. The initial code has a following form:
int top = Int32.MaxValue; . . .
foreach (Control c in Controls)
{
if (top == Int32.MaxValue || top > c.Top) top = c.Top;
//the same for bottom, left, right
}
After some thinking I come up with the following solution:
List<Control> controls =
new List<Control>(this.Controls.Cast<Control>());
Rectangle rect = controls.Aggregate<Control, Rectangle>(
controls[0].Bounds, (r, c) => Rectangle.Union(r, c.Bounds));
Looks better, yeh?

