Fabrice's weblog

Tools and Source

News

My .NET Toolbox
An error occured. See the script errors signaled by your web browser.
No tools selected yet
.NET tools by SharpToolbox.com

Read sample chapters or buy LINQ in Action now!
Our LINQ book is also available on AMAZON

.NET jobs

Emplois .NET

Tuneo

ASP.NET Hosting transatlantys

Contact

Me

Others

Selected content

Archives

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.
Posted: Mar 23 2005, 06:14 PM by Fabrice Marguerie | with 7 comment(s)
Filed under:

Comments

Brad said:

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

# November 8, 2007 2:51 PM

rossisdead said:

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.

# September 17, 2009 4:34 PM

Someoneelse said:

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

{

}

# December 1, 2009 8:09 AM