Introduction
This is a fast, reliable method to determine if you are currently in Design Mode.
Background
Background is the usual for this one - I needed to do certain things with my custom control in design mode. Noting fairly quickly that the DesignMode
property was not reliable, I did the usual searches, and came up with a number of methods (including Mika Wendelius' [^] article here[^]). The possibilities were:
It also should be noted that once a module if found to be in design mode or not, the mode does not change. As such, once the mode has been determined, any subsequent calls should just return the previous result, rather than going through the process all over again.
The final result I came up with is:
static class DesignModeExtension {
static bool? _isinDesignMode = null;
public static bool IsInDesignMode(this Control control) {
if (!_isinDesignMode.HasValue) {
_isinDesignMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
while (!_isinDesignMode.Value && control != null) {
_isinDesignMode = control.Site?.DesignMode ?? false;
control = control.Parent;
}
}
return _isinDesignMode.Value;
}
}
Firstly, I check whether the mode has already been determined. If it hasn't, I proceed to determine it.
The determination starts with the fastest method, albeit unreliable. However, it is only the "false
" return value that is unreliable. If this test returns true
, then there is no need to traverse the controls to see if they are in design mode. Finally, if needed, I traverse the control's parents until I either find one that confirms I am in design mode, or I reach the end, in which case I can be certain that the application is not in design mode. I then save the final result before returning it to the caller.
Using the Code
The attached source is not in any project - it is simply a .cs file containing the definition. To install it, simply add this file to your project.
Using the extension is as simple as if (this.IsInDesignMode())
. This can be called from anywhere within a control's scope.
Been programming for 40 years now, starting when I was 13 on DEC PDP 11 (back in the day of paper tape storage, and hex switch boot procedures). Got right into micro-computers from an early age, with machines like the Dick Smith Sorcerer and the CompuColor II. Started CP/M and MS-DOS programming in the mid 1980's. By the end of the '80's, I was just starting to get a good grip on OOP (Had Zortech C++ V1.0).
Got into ATL and COM programming early 2002. As a result, my gutter vocabulary has expanded, but it certainly keeps me off the streets.
Recently, I have had to stop working full time as a programmer due to permanent brain damage as a result of a tumour (I just can't keep up the pace required to meet KPI's). I still like to keep my hand in it, though, and will probably post more articles here as I discover various tricky things.