VB.Net 控件列表

VB.Net List of Controls

我想获取所有控件的列表;我设法在下面的代码中做到了这一点;问题是这确实只列出了容器外的控件。我想获取所有控件的列表,包括容器内的控件(例如 TabControl 内的控件)。我的问题是:如何在 VB.Net?

中执行此操作
Sub ListAllControls()
    Me.RichTextBox1.Clear()
    Dim MekdamCTL As Control
    For Each MekdamCTL In Me.Controls
        Me.RichTextBox1.AppendText("Control: " & MekdamCTL.Name & Environment.NewLine)
    Next
    Me.RichTextBox1.AppendText("How to include ALL Controls in ALL Containers, such as Controls in TabControl ??")
End Sub

在此先感谢您的帮助 and/or 评论。

这比您需要的稍微复杂一些,但是以下函数 returns 任何给定类型的所有控件并可选择搜索任何嵌入式容器

''' <summary>Get all Controls of a specified type within a container and optionally any embedded containers</summary>
''' <typeparam name="ctrlType">The type of Control to be searched for (must inherit from Control)</typeparam>
''' <param name="parent">The top level container</param>
''' <param name="searchContainers">True if embedded containers are to be searched</param>
''' <returns>IEnumerable with all Controls of the specified type that were found</returns>
Function GetControlsOfType(Of ctrlType As Control)(parent as Control, searchContainers As Boolean) As IEnumerable(Of ctrlType)
    Dim ctrls As New List(Of ctrlType)
    For Each ctrl As Control In parent.Controls 
        If TypeOf ctrl Is ctrlType Then ctrls.Add(DirectCast(ctrl, ctrlType))
        If searchContainers AndAlso ctrl.Controls.Count > 0 Then ctrls.AddRange(GetControlsOfType(Of ctrlType)(ctrl, searchContainers))
    Next
    Return ctrls
End Function

如果你想列出任何类型的所有控件,你可以这样调用:

For Each ctrl As Control In GetControlsOfType(Of Control)(Me, True)
    Me.RichTextBox1.AppendText("Control: " & ctrl.Name & vbCrLf)
Next

您需要一个可以从主窗体调用的递归函数

Public Sub ListControls(coll As Control.ControlCollection)
    for each ctr in coll
       Me.RichTextBox1.AppendText("Control: " & ctr.Name & Environment.NewLine)
       if ctr.Controls.Count > 0 Then
          ListControls(ctr.Controls)
       End if
    Next
End Sub

从您的主窗体调用它

ListControls(Me.Controls)

试一试:

    'this loop will get all the controls on the form
    'no matter what the level of container nesting

    Dim ctrl As Control = Me.GetNextControl(Me, True)
    Do Until ctrl Is Nothing
        RichTextBox1.AppendText("Control: " & ctrl.Name & Environment.NewLine)
        ctrl = Me.GetNextControl(ctrl, True)
    Loop

使用此方法无需检查或递归。

这个可以用吗:

Private Sub frmWRMenu_Activated(sender As Object, e As EventArgs) Handles Me.Activated

Dim k As New List(Of String)
     Dim myNumber = 0
     Dim myCtrl As Control = Me
Repeat:
    For a = 1 To myCtrl.Controls.Count
        k.Add(myCtrl.Controls(a - 1).Name)
        Debug.Print(myCtrl.Controls(a - 1).Name)
    Next
    If (myNumber + 1) <= k.Count Then
        myCtrl = Me.Controls.Find(k(myNumber ), True)(0)
        myNumber += 1
        GoTo Repeat
    End If
End Sub