| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- internal class FindSpecificControls
- {
- public static List<T> FindControlsByInterface<T>(Control parent) where T : class
- {
- var controlsWithInterface = new List<T>();
- foreach (Control control in GetAllControls(parent))
- {
- if (control is T interfaceControl)
- {
- controlsWithInterface.Add(interfaceControl);
- }
- }
- return controlsWithInterface;
- }
- // 递归获取所有嵌套控件
- private static IEnumerable<Control> GetAllControls(Control container)
- {
- foreach (Control control in container.Controls)
- {
- yield return control;
- if (control.HasChildren)
- {
- foreach (Control child in GetAllControls(control))
- {
- yield return child;
- }
- }
- }
- }
- }
|