前段时间我实现了一个解决方案,在该解决方案中我创建了自定义基本表单和控件实现,添加了一个属性并覆盖了 OnLoad 方法:
public partial class FormBase : Form
{
public FormBase ()
{
this.InitializeComponent();
}
protected ConsistencyManager ConsistencyManager { get; private set; }
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
if (this.ConsistencyManager == null)
{
this.ConsistencyManager = new ConsistencyManager(this);
this.ConsistencyManager.MakeConsistent();
}
}
}
ConsistencyManager 类查找所有控件、组件,还支持在特定控件中搜索自定义子控件。从 MakeConsistent 方法复制/粘贴代码:
public void MakeConsistent()
{
if (this.components == null)
{
List<IComponent> additionalComponents = new List<IComponent>();
// get all controls, including the current one
this.components =
this.GetAllControls(this.parentControl)
.Concat(GetAllComponents(this.parentControl))
.Concat(new Control[] { this.parentControl });
// now find additional components, which are not present neither in Controls collection nor in components
foreach (var component in this.components)
{
IAdditionalComponentsProvider provider = GetAdditinalComponentsProvider(component.GetType().FullName);
if (provider != null)
{
additionalComponents.AddRange(provider.GetChildComponents(component));
}
}
if (additionalComponents.Count > 0)
{
this.components = this.components.Concat(additionalComponents);
}
}
this.MakeConsistent(this.components);
}
如果有人想要完整的样本或来源,请告诉我。
最好的问候,兹冯科
PS:以同样的方式,我还创建了计算主线程调用次数的性能计数器。