Revisiting this question, I have now 'discovered' 5 different ways of doing this, which are as follows:
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"))
}
To try and get a hang on the three solutions proposed, I created a little test solution - with three projects:
- TestApp (winforms application),
- SubControl (dll)
- SubSubControl (dll)
I then embedded the SubSubControl in the SubControl, then one of each in the TestApp.Form.
This screenshot shows the result when running.
This screenshot shows the result with the form open in Visual Studio:
Conclusion: It would appear that without reflection the only one that is reliable within the constructor is LicenseUsage, and the only one which is reliable outside the constructor is 'IsDesignedHosted' (by BlueRaja below)
PS: See ToolmakerSteve's comment below (which I haven't tested): "Note that IsDesignerHosted answer has been updated to include LicenseUsage..., so now the test can simply be if (IsDesignerHosted). An alternative approach is test LicenseManager in constructor and cache the result."
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…