I created some User Controls for my Windows Applications. They worked properly during run time. On some of these controls, certain tasks were performed in the load event. Sometimes these controls would exhibit strange behavior at design time. The things I was doing were not needed during design, so I looked for a way to disable these tasks during design time.
Each component has a property called DesignMode. This seemed like the solution but DesignMode is NOT propagated when a control is placed in a container.
Many people list the same solution, shown below. This only works if you are developing code in the Microsoft IDE (Visual Studio). Since this is the only environment I work in, this is not a problem.
if (System.Diagnostics.Process.GetCurrentProcess().ProcessName != "devenv")
{
// Do Tasks here
}
I do not like to cut and paste code in multiple places. I turned the code into a static property in a tools class. Everything worked well for months.
public static bool DesignMode
{
get { return System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv"; }
}
if (!Tools.DesignMode)
{
// Do Tasks here
}
Then, I started using the User Controls as a cell of a DataGridViewCell. A DataGridViewCell is cloned frequently. There were some deep cloning objects that could not be cloned during design time. Using my static DesignMode property, the problem was solved. Weeks later, I was copying 400 rows of data from 2008 to 2009. It took close to 10 Seconds and the DataGridView froze in an ugly display while waiting for completion.
I took a few days and tracked it down to the DesignMode property. I kicked myself for NOT seeing the obvious. I made the change shown below. Now my 400 row copy completed in less than a second. My second benefit come from what I did do that was smart. Since static DesignMode property was used everywhere, all the DataGridView controls received a performance boost. Some grids were sluggish but acceptable. Now every grid zooms with performance.
private static bool? _DesignMode = null;
public static bool DesignMode
{
get
{
if (!_DesignMode.HasValue)
_DesignMode = System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv";
return _DesignMode.Value;
}
}
With Lazy Loading, I only called the time expensive GetCurrentProcess method once. But the story does not end here. In C# Architect I found a better way to test for DesignMode. I searched more on the Internet, only to find a couple of Microsoft forums suggesting this same answer. This new way is working well for my applications.
private static bool? _DesignMode = null;
public static bool DesignMode
{
get
{
if (!_DesignMode.HasValue)
_DesignMode = System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime;
return _DesignMode.Value;
}
}