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.
- 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.