我建议你用一种更通用的方法:
private void Form1_Load(object sender, EventArgs e)
{
foreach (var controlTag in XDocument.Load("settings.xml").Root.Elements())
{
var controlType = Type.GetType(string.Format("System.Windows.Forms.{0}, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", controlTag.Name.LocalName), false);
if (controlType == null || !typeof(Control).IsAssignableFrom(controlType))
{
continue;
}
var control = (Control)Activator.CreateInstance(controlType);
control.Text = controlTag.Attribute("Content").Value;
control.Location = new Point(
int.Parse(controlTag.Attribute("LocationX").Value),
int.Parse(controlTag.Attribute("LocationY").Value)
);
control.BackColor = Color.Transparent;
control.MouseClick += mouseClick;
control.MouseDown += mouseDown;
control.MouseMove += mouseMove;
control.MouseUp += mouseUp;
control.MouseDoubleClick += mouseDoubleClick;
Controls.Add(control);
}
}
至于颜色,您可以向XML文件添加一个属性,该属性将指向要设置和使用反射的控件的属性名。例如:
<?xml version="1.0" encoding="utf-8"?>
<cs>
<Label Content="Double-click to edit." LocationX="583" LocationY="254" A="255" R="255" G="255" B="255" ColorProperty="ForeColor" />
<LinkLabel Content="Double-click to edit." LocationX="613" LocationY="251" A="255" R="0" G="0" B="0" ColorProperty="LinkColor" />
</cs>
顺便说一下,XAML已经提供了您在这里试图实现的许多功能。当然,它假定的是WPF接口,这可能不是您的情况。