枚举表单控件

时间:2010-10-14 15:43:44

标签: c# winforms powershell system.componentmodel

我有这个C#代码来枚举Form实例的控件:

private void button1_Click(object sender, EventArgs e)
{
    textBox1.Text = "";

    Form2 form2 = new Form2();

    foreach (Control control in form2.Controls)
    {
        PropertyDescriptorCollection properties = 
            TypeDescriptor.GetProperties(control);

        foreach (PropertyDescriptor property in properties)
        {
            textBox1.Text += (property.Name + Environment.NewLine);
        }
    }
}

这将列出TextBox中Form Form2的所有控件名称。这是我尝试在PowerShell中重现此代码:

$form = New-Object System.Windows.Forms.Form

foreach($control in $form.Controls)
{
    $properties = 
        [System.ComponentModel.TypeDescriptor]::GetProperties($control)

    foreach($property in $properties)
    {
        $property.Name
    } 
}

但这不起作用。 $ form.Control似乎是空的,所以永远不会输入foreach循环。如何让上述C#代码在PowerShell中运行?

[编辑1]

上面的代码显然有一个没有控件的表单。这里是更新的PowerShell代码,其中包含一个添加到其Controls集合中的Button的表单,但是(看似)与不枚举Controls集合的结果相同:

$form = New-Object System.Windows.Forms.Form
$button = New-Object System.Windows.Forms.Button
$form.Controls.Add($Button)

$form.Controls.Count

foreach($control in $form.Controls)
{
    $properties = 
        [System.ComponentModel.TypeDescriptor]::GetProperties($control)

    foreach($property in $properties)
    {
        $property.DisplayName
    } 
}

[编辑2]

如果我检查$ property类型:

foreach($property in $properties)
{
    $property.GetType().FullName
} 

GetType()返回:

System.ComponentModel.PropertyDescriptorCollection

我期望PropertyDescriptor。

2 个答案:

答案 0 :(得分:2)

在你的C#代码中,你可能有一个定义为Form2的类,它有控件。在你的powershell中,你正在加载一个没有任何控件的香草System.Windows.Forms.Form。

答案 1 :(得分:1)

你只需要手动.GetEnumerator() - 我不确定为什么Powershell没有正确展开它。

$form = New-Object System.Windows.Forms.Form
$button = New-Object System.Windows.Forms.Button
$form.Controls.Add($Button)

$form.Controls.Count

foreach($control in $form.Controls)
{
    $properties = 
        [System.ComponentModel.TypeDescriptor]::GetProperties($control)

    foreach($property in $properties.GetEnumerator())
    {
        $property.DisplayName
    } 
}