重新审视这个问题,我现在"发现"了5种不同的解决方法,它们如下:
System.ComponentModel.DesignMode property
System.ComponentModel.LicenseManager.UsageMode property
private string ServiceString()
{
if (GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null)
return "Present";
else
return "Not present";
}
public bool IsDesignerHosted
{
get
{
Control ctrl = this;
while(ctrl != null)
{
if((ctrl.Site != null) && ctrl.Site.DesignMode)
return true;
ctrl = ctrl.Parent;
}
return false;
}
}
public static bool IsInDesignMode()
{
return System.Reflection.Assembly.GetExecutingAssembly()
.Location.Contains("VisualStudio"))
}
为了try 理解提出的三个解决方案,我创建了一个小型测试解决方案-包含三个项目:
- TestApp(WinForms应用程序),
- 子控件(DLL)
- Sub子控件(DLL)
然后,我将SubSubControl嵌入到SubControl中,然后将每个嵌入到TestApp.Form中.
此屏幕截图显示了运行时的结果.
此屏幕截图显示了在Visual Studio中打开表单后的结果:
结论:without reflection似乎是唯一可靠的within建造商是许可使用的,而唯一可靠的outside建造商是"IsDesignedHosted"(以下BlueRaja)
PS:请参阅ToolmakerSteve下面的 comments (我还没有测试):"注意,IsDesignerHosted个答案已经更新,包括LicenseUsage…,所以现在测试可以是if(IsDesignerHosted).另一种方法是test LicenseManager in constructor and cache the result."