FindSpecificControls.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows.Forms;
  9. internal class FindSpecificControls
  10. {
  11. public static List<T> FindControlsByInterface<T>(Control parent) where T : class
  12. {
  13. var controlsWithInterface = new List<T>();
  14. foreach (Control control in GetAllControls(parent))
  15. {
  16. if (control is T interfaceControl)
  17. {
  18. controlsWithInterface.Add(interfaceControl);
  19. }
  20. }
  21. return controlsWithInterface;
  22. }
  23. // 递归获取所有嵌套控件
  24. private static IEnumerable<Control> GetAllControls(Control container)
  25. {
  26. foreach (Control control in container.Controls)
  27. {
  28. yield return control;
  29. if (control.HasChildren)
  30. {
  31. foreach (Control child in GetAllControls(control))
  32. {
  33. yield return child;
  34. }
  35. }
  36. }
  37. }
  38. }