最近遇到一个问题,如何确定设计时和运行时。可能我们某些控件在设计时是不可达的,但当程序运行起来的时候,我们会正确处理这个控件。但是VS不知道这一点。它只会运行构造函数,将所有设计时的控件显示出来,如果该控件在设计时不可达,并导致异常,那么就会导致整个设计页面挂掉。
这时我们需要判断设计时与运行时:
if (GetService(Type.GetType("System.ComponentModel.Design.IDesignerHost")) == Nothing )
Me.button1.Text = "Button1 in runtime";
else
Me.button1.Text = "Button1 in design";
这是MSDN上的关于GetService的介绍:http://msdn.microsoft.com/zh-cn/library/system.componentmodel.component.getservice.aspx
上面这段代码的原理是,当处于design-time时,所有的控件一定是交由designer控制的。
这里还有另外一种方法:
If System.ComponentModel.LicenseManager.UsageMode = System.ComponentModel.LicenseUsageMode.Runtime Then
Me.Button1.Text = "Button1 in runtime"
Else
Me.Button1.Text = "Button1 in design"
End If