I have a function which loops over the controls on a form and checks to see if it's in a given rect, and then adds it or doesn't add it to a list<>
. The parameter bContained
is used to determine if we want a list of "in the rect" or "not in the rect" controls.
List<Control> getControls(Control container, Rectangle rect, bool bContained = false)
{
List<Control> Selected = new List<Control>();
rect = RectangleToClient(rect);
foreach (Control ctl in container.Controls)
{
//Do we want selected or non-selected controls
if (bContained)
{
if (rect.IntersectsWith(ctl.Bounds)) Selected.Add(ctl);
foreach (Control ct in ctl.Controls) Selected.Add(ct);
}
else
{
if (!rect.IntersectsWith(ctl.Bounds)) Selected.Add(ctl);
foreach (Control ct in ctl.Controls) Selected.Add(ct);
}
}
return Selected;
}