using System.Collections; using System.Collections.Generic; namespace System.Windows.Forms { public partial class Control { public class ControlCollection : CollectionBase { private Control owner; public Control this[int index] => (Control)List[index]; public int Add(Control control) { int index = IndexOf(control); if (index != -1) return index; if (control.Parent != null) control.Parent = null; var result = List.Add(control); owner.AddChild(control); control.SetParent(owner); if (control.Dock != DockStyle.None) owner.UpdateLayout(); owner.DoControlAdded(control); return result; } public void AddRange(Control[] controls) { foreach (Control c in controls) Add(c); } public void Remove(Control control) { List.Remove(control); owner.RemoveChild(control); control.SetParent(null); if (control.Dock != DockStyle.None) owner.UpdateLayout(); owner.DoControlRemoved(control); } public new void RemoveAt(int index) => Remove(this[index]); public new void Clear() { while (Count > 0) Remove(this[0]); } public int IndexOf(Control control) => List.IndexOf(control); public bool Contains(Control control) => List.Contains(control); public void SetChildIndex(Control control, int index) { List.Remove(control); List.Insert(index, control); owner.RemoveChild(control); owner.SetChildIndex(control, index); control.SetParent(owner); if (control.Dock != DockStyle.None) owner.UpdateLayout(); } public void Insert(int index, Control control) { Add(control); SetChildIndex(control, index); } private void Find(string name, bool searchChildren, List result) { foreach (Control c in List) { if (c.Name == name) result.Add(c); if (searchChildren) c.Controls.Find(name, searchChildren, result); } } public Control[] Find(string name, bool searchChildren) { List result = new List(); Find(name, searchChildren, result); return result.ToArray(); } public ControlCollection(Control owner) { this.owner = owner; } } } }