gpt4 book ai didi

c# - 枚举表单控件

转载 作者:行者123 更新时间:2023-11-30 22:43:29 24 4
gpt4 key购买 nike

我有这个 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 代码,其中包含一个将 Button 添加到其 Controls 集合的表单,但具有(看似)相同的未枚举 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 的位置。

最佳答案

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

关于c# - 枚举表单控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3935000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com