# Monday, 28 June 2010

The other day, Visual Studio 2008 kept crashing due to an issue with one of our user controls. When I opened a WinForm which contained the control, VS would initialize everything, get to an exception and crash. The exception was caused by the user control running code that it should not have in the designer. A quick search turned up this post on stackoverflow

  1. if (LicenseManager.UsageMode == LicenseUsageMode.Runtime) {
  2.   ...
  3. }

This code works in most scenarios, but failed for me. More searching turned up a post by Andre de Cavaignac

  1. public bool IsDesignerHosted {
  2.   get {
  3.     Control ctrl = this;
  4.     while (ctrl != null) {
  5.       if (ctrl.Site == null)
  6.         return false;
  7.       if (ctrl.Site.DesignMode == true)
  8.         return true;
  9.       ctrl = ctrl.Parent;
  10.     }
  11.     return false;
  12.   }
  13. }

I found that mostly worked as well. I ended up having to combine them to detect correctly 100% of the time if the control was designer hosted. I created it as an extension method, and here is the result

  1. /// <summary>
  2. /// Used to detect whether the control is being hosted on the surface of a form at design-time,
  3. /// since the DesignMode property no longer works once the control has been compiled and
  4. /// hosted on the surface of another design-time control.
  5. /// </summary>
  6. public static bool IsDesignerHosted(this Control ctrl) {
  7.   get {
  8.     while (ctrl != null) {
  9.       if (ctrl.Site == null)
  10.         return false;
  11.       if (ctrl.Site.DesignMode)
  12.         return true;
  13.       ctrl = ctrl.Parent;
  14.     }
  15.  
  16.     return (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
  17.   }
  18. }
C# | WinForms
Monday, 28 June 2010 17:45:00 (Alaskan Daylight Time, UTC-08:00)