要收集 WinForm 控件,可以使用反射来获取窗体中的控件。以下是一个示例代码:
using System;
using System.Reflection;
using System.Windows.Forms;
namespace WinFormControlsCollector
{
class Program
{
static void Main(string[] args)
{
// 创建一个 WinForm 窗体
Form form = new Form();
form.Controls.Add(new Button());
form.Controls.Add(new TextBox());
form.Controls.Add(new Label());
// 使用反射获取窗体中的控件
var controls = GetControls(form);
// 打印控件信息
foreach (var control in controls)
{
Console.WriteLine(control.Name);
}
}
// 使用反射获取窗体中的控件
static Control[] GetControls(Form form)
{
// 获取窗体的类型
Type formType = form.GetType();
// 使用反射获取窗体中的控件字段
FieldInfo[] controlFields = formType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
// 创建控件数组
Control[] controls = new Control[controlFields.Length];
// 将控件字段的值赋给控件数组
for (int i = 0; i < controlFields.Length; i++)
{
controls[i] = (Control)controlFields[i].GetValue(form);
}
return controls;
}
}
}
在上述代码中,我们首先创建了一个包含不同类型控件的 WinForm 窗体。然后,使用 GetControls
方法通过反射获取窗体中的控件。最后,我们打印了控件的名称。
请注意,这只是一个示例,实际使用中可能需要根据具体情况进行调整。