ASP.NET Hosting

Windows Forms designer and DesignMode property issues

It's interesting to know how the Windows Forms designer in Visual Studio loads forms. Did you ever wonder how it is possible for you to design an instance of a form while the underlying class is not completed and compiled? Raghavendra Prabhu explains how it works.

One problem that remains unanswered is how to detect a form is in design mode, to avoid accessing to run-time resources. One would think the DesignMode property is the solution.
Let's consider the following constructor for example:

public MyClass()
{
  if (!DesignMode)
  {
    _Connection = new DatabaseConnection("aceofbase");
    _Connection.Open();
  }
}


The small problem with the DesignMode property is that it is not always telling the full truth!
The DesignMode property isn't set to true in the constructor.
Remember, there's no real magic here.
Visual Studio .NET creates your object as it parses the InitializeComponent() method. Once the object is constructed, Visual Studio .NET keeps track of the objects it creates, and simply says: newlyCreatedObject.DesignMode = true

There is no definitive solution to this problem.
All kinds of workarounds are used.
  • We could call GetService(typeof(IDesignerHost)) and see if it returns something.
  • Other option: test System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime
  • Some are comparing System.Diagnostics.Process.GetCurrentProcess().ProcessName to "devenv" to see if the form is hosted in Visual Studio. But I don't like this one because in many cases it won't work (like with VS add-ins).
On a related note, Brian Pepin has written about the problems with designing abstract forms.

3 Comments

  • Put your run-time specific code in the control's Load event handler and wrap it with an "if (!DesignMode)"

  • I just wanted to add this as I was trying to figure out a similar problem with the DesignMode property.

    I found that you can not check for DesignMode until after the control's handle has been created. Switching my run-time only stuff to checking there fixed all my problems.

  • if (System.ComponentModel.LicenseManager.CurrentContext.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)
    {

    }

Comments have been disabled for this content.