public Control[] GetAllControls(Control top)
{
ArrayList buf = new ArrayList();
foreach (Control c in top.Controls)
{
buf.Add(c);
buf.AddRange(GetAllControls(c));
}
return (Control[])buf.ToArray(typeof(Control));
}
すべてのコントロールを再帰的に取得するメソッド(C#)
Public Function GetAllControls(ByVal top As Control) As Control()
Dim buf As ArrayList = New ArrayList
For Each c As Control In top.Controls
buf.Add(c)
buf.AddRange(GetAllControls(c))
Next
Return CType(buf.ToArray(GetType(Control)), Control())
End Function
このGetAllControlsメソッドを利用したコード例を次に示す。このコードはVisual Studio .NETで作成したWindowsアプリケーションにおいて、Buttonコントロールのイベント・ハンドラとして記述した場合を想定している。コード中のthis(VB.NETではMe)はフォームを参照している。
private void button1_Click(object sender, System.EventArgs e)
{
Control[] all = GetAllControls(this);
foreach (Control c in all)
{
Console.WriteLine(c.Name);
}
}
GetAllControlsメソッドの呼び出し例(C#)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim all As Control() = GetAllControls(Me)
For Each c As Control In all
Console.WriteLine(c.Name)
Next
End Sub
GetAllControlsメソッドの呼び出し例(VB.NET)
次のようなデザインのフォームに対して上記のコードを実行すると、下に示すような出力がVisual Studio .NETの[出力]ウィンドウに表示される。