<p>Has anyone found a useful solution to the DesignMode problem when developing controls?</p>

<p>The issue is that if you nest controls then DesignMode only works for the first level.  The second and lower levels DesignMode will always return FALSE.</p>

<p>The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE.</p>

<p>The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name.  In addition this strange route is very slow.  So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE.</p>

<p>A nice clean way to determine DesignMode is in order.  Acually getting Microsoft to fix it internally to the framework would be even better!</p>

[{'answer_id': 34696, 'author': 'Will Dean', 'author_id': 987, 'author_profile': 'https://Stackoverflow.com/users/987', 'pm_score': 2, 'selected': False, 'text': "<p>I've never been caught by this myself, but couldn't you just walk back up the Parent chain from the control to see if DesignMode is set anywhere above you?</p>\n"}, {'answer_id': 34741, 'author': 'Craig', 'author_id': 2894, 'author_profile': 'https://Stackoverflow.com/users/2894', 'pm_score': 1, 'selected': False, 'text': '<p>DesignMode is a private property (from what I can tell).  The answer is to provide a public property that exposes the DesignMode prop.  Then you can cascasde back up the chain of user controls until you run into a non-user control or a control that is in design mode.  Something like this....</p>\n\n<pre><code>  public bool RealDesignMode()\n  {\n     if (Parent is MyBaseUserControl)\n     {\n        return (DesignMode ? true : (MyBaseUserControl) Parent.RealDesignMode;\n     }\n\n     return DesignMode;\n  }\n</code></pre>\n\n<p>Where all your UserControls inherit from MyBaseUserControl.  Alternatively you could implement an interface that exposes the "RealDeisgnMode".  </p>\n\n<p>Please note this code is not live code, just off the cuff musings. :)</p>\n'}, {'answer_id': 34842, 'author': 'Will Dean', 'author_id': 987, 'author_profile': 'https://Stackoverflow.com/users/987', 'pm_score': 1, 'selected': False, 'text': '<p>I hadn\'t realised that you can\'t call Parent.DesignMode (and I have learned something about \'protected\' in C# too...)</p>\n\n<p>Here\'s a reflective version:  (I suspect there might be a performance advantage to making designModeProperty a static field)</p>\n\n<pre><code>static bool IsDesignMode(Control control)\n{\n    PropertyInfo designModeProperty = typeof(Component).\n      GetProperty("DesignMode", BindingFlags.Instance | BindingFlags.NonPublic);\n\n    while (designModeProperty != null &amp;&amp; control != null)\n    {\n        if((bool)designModeProperty.GetValue(control, null))\n        {\n            return true;\n        }\n        control = control.Parent;\n    }\n    return false;\n}\n</code></pre>\n'}, {'answer_id': 346806, 'author': 'hopla', 'author_id': 40972, 'author_profile': 'https://Stackoverflow.com/users/40972', 'pm_score': 5, 'selected': False, 'text': "<p>Why don't you check LicenseManager.UsageMode.\nThis property can have the values LicenseUsageMode.Runtime or LicenseUsageMode.Designtime.</p>\n\n<p>Is you want code to only run in runtime, use the following code:</p>\n\n<pre><code>if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)\n{\n  bla bla bla...\n}\n</code></pre>\n"}, {'answer_id': 708594, 'author': 'Benjol', 'author_id': 11410, 'author_profile': 'https://Stackoverflow.com/users/11410', 'pm_score': 7, 'selected': True, 'text': '<p>Revisiting this question, I have now \'discovered\' 5 different ways of doing this, which are as follows:</p>\n\n<pre><code>System.ComponentModel.DesignMode property\n\nSystem.ComponentModel.LicenseManager.UsageMode property\n\nprivate string ServiceString()\n{\n    if (GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null) \n        return "Present";\n    else\n        return "Not present";\n}\n\npublic bool IsDesignerHosted\n{\n    get\n    {\n        Control ctrl = this;\n\n        while(ctrl != null)\n        {\n            if((ctrl.Site != null) &amp;&amp; ctrl.Site.DesignMode)\n                return true;\n            ctrl = ctrl.Parent;\n        }\n        return false;\n    }\n}\npublic static bool IsInDesignMode()\n{\n    return System.Reflection.Assembly.GetExecutingAssembly()\n         .Location.Contains("VisualStudio"))\n}\n</code></pre>\n\n<p>To try and get a hang on the three solutions proposed, I created a little test solution - with three projects: </p>\n\n<ul>\n<li>TestApp (winforms application), </li>\n<li>SubControl (dll) </li>\n<li>SubSubControl (dll)</li>\n</ul>\n\n<p>I then embedded the SubSubControl in the SubControl, then one of each in the TestApp.Form.</p>\n\n<p>This screenshot shows the result when running.\n<img src="https://i.stack.imgur.com/pylfS.png" alt="Screenshot of running"></p>\n\n<p>This screenshot shows the result with the form open in Visual Studio:</p>\n\n<p><img src="https://i.stack.imgur.com/4cgxt.png" alt="Screenshot of not running"></p>\n\n<p>Conclusion: It would appear that <em>without reflection</em> the only one that is reliable <em>within</em> the constructor is LicenseUsage, and the only one which is reliable <em>outside</em> the constructor is \'IsDesignedHosted\' (by <a href="https://stackoverflow.com/questions/34664/designmode-with-controls/2693338#2693338">BlueRaja</a> below)</p>\n\n<p>PS: See ToolmakerSteve\'s comment below (which I haven\'t tested): "Note that <a href="https://stackoverflow.com/a/2693338/199364">IsDesignerHosted</a> answer has been updated to include LicenseUsage..., so now the test can simply be if (IsDesignerHosted). An alternative approach is <a href="https://stackoverflow.com/a/2849244/199364">test LicenseManager in constructor and cache the result</a>."</p>\n'}, {'answer_id': 2693338, 'author': 'BlueRaja - Danny Pflughoeft', 'author_id': 238419, 'author_profile': 'https://Stackoverflow.com/users/238419', 'pm_score': 5, 'selected': False, 'text': '<p>From <a href="http://decav.com/blogs/andre/archive/2007/04/18/1078.aspx" rel="noreferrer">this page</a>:</p>\n\n<p><em>(<strong>[Edit 2013]</strong> Edited to work in constructors, using the method provided by @hopla)</em></p>\n\n<pre><code>/// &lt;summary&gt;\n/// The DesignMode property does not correctly tell you if\n/// you are in design mode.  IsDesignerHosted is a corrected\n/// version of that property.\n/// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305\n/// and http://stackoverflow.com/a/2693338/238419 )\n/// &lt;/summary&gt;\npublic bool IsDesignerHosted\n{\n    get\n    {\n        if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n            return true;\n\n        Control ctrl = this;\n        while (ctrl != null)\n        {\n            if ((ctrl.Site != null) &amp;&amp; ctrl.Site.DesignMode)\n                return true;\n            ctrl = ctrl.Parent;\n        }\n        return false;\n    }\n}\n</code></pre>\n\n<p>I\'ve submitted <a href="https://connect.microsoft.com/VisualStudio/feedback/details/553305/designmode-always-returns-false-winforms-designer#" rel="noreferrer">a bug-report</a> with Microsoft; I doubt it will go anywhere, but vote it up anyways, as this is obviously a bug (whether or not it\'s <em>"by design"</em>).</p>\n'}, {'answer_id': 2849244, 'author': 'Jonathan', 'author_id': 6910, 'author_profile': 'https://Stackoverflow.com/users/6910', 'pm_score': 3, 'selected': False, 'text': '<p>I use the LicenseManager method, but cache the value from the constructor for use throughout the lifetime of the instance.</p>\n\n<pre><code>public MyUserControl()\n{\n    InitializeComponent();\n    m_IsInDesignMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);\n}\n\nprivate bool m_IsInDesignMode = true;\npublic bool IsInDesignMode { get { return m_IsInDesignMode; } }\n</code></pre>\n\n<hr>\n\n<p>VB version:</p>\n\n<pre><code>Sub New()\n    InitializeComponent()\n\n    m_IsInDesignMode = (LicenseManager.UsageMode = LicenseUsageMode.Designtime)\nEnd Sub\n\nPrivate ReadOnly m_IsInDesignMode As Boolean = True\nPublic ReadOnly Property IsInDesignMode As Boolean\n    Get\n        Return m_IsInDesignMode\n    End Get\nEnd Property\n</code></pre>\n'}, {'answer_id': 3822767, 'author': 'husayt', 'author_id': 15461, 'author_profile': 'https://Stackoverflow.com/users/15461', 'pm_score': 3, 'selected': False, 'text': '<p>This is the method I use inside forms:</p>\n\n<pre><code>    /// &lt;summary&gt;\n    /// Gets a value indicating whether this instance is in design mode.\n    /// &lt;/summary&gt;\n    /// &lt;value&gt;\n    ///     &lt;c&gt;true&lt;/c&gt; if this instance is in design mode; otherwise, &lt;c&gt;false&lt;/c&gt;.\n    /// &lt;/value&gt;\n    protected bool IsDesignMode\n    {\n        get { return DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime; }\n    }\n</code></pre>\n\n<p>This way, the result will be correct, even if either of DesignMode or LicenseManager properties fail.</p>\n'}, {'answer_id': 7281838, 'author': 'Boris B.', 'author_id': 382783, 'author_profile': 'https://Stackoverflow.com/users/382783', 'pm_score': 2, 'selected': False, 'text': "<p>Since none of the methods are reliable (DesignMode, LicenseManager) or efficient (Process, recursive checks) I'm using a <code>public static bool Runtime { get; private set }</code> at program level and explicitly setting it inside the Main() method. </p>\n"}, {'answer_id': 12526432, 'author': 'juFo', 'author_id': 187650, 'author_profile': 'https://Stackoverflow.com/users/187650', 'pm_score': 2, 'selected': False, 'text': '<p>We use this code with success:</p>\n\n<pre><code>public static bool IsRealDesignerMode(this Control c)\n{\n  if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)\n    return true;\n  else\n  {\n    Control ctrl = c;\n\n    while (ctrl != null)\n    {\n      if (ctrl.Site != null &amp;&amp; ctrl.Site.DesignMode)\n        return true;\n      ctrl = ctrl.Parent;\n    }\n\n    return System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv";\n  }\n}\n</code></pre>\n'}, {'answer_id': 35041620, 'author': 'user2785562', 'author_id': 2785562, 'author_profile': 'https://Stackoverflow.com/users/2785562', 'pm_score': 2, 'selected': False, 'text': '<p>My suggestion is an optimization of @blueraja-danny-pflughoeft <a href="https://stackoverflow.com/a/2693338/2785562">reply</a>.\nThis solution doesn\'t calculate result every time but only at the first time (an object cannot change UsageMode from design to runtime) </p>\n\n<pre><code>private bool? m_IsDesignerHosted = null; //contains information about design mode state\n/// &lt;summary&gt;\n/// The DesignMode property does not correctly tell you if\n/// you are in design mode.  IsDesignerHosted is a corrected\n/// version of that property.\n/// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305\n/// and https://stackoverflow.com/a/2693338/238419 )\n/// &lt;/summary&gt;\n[Browsable(false)]\npublic bool IsDesignerHosted\n{\n    get\n    {\n        if (m_IsDesignerHosted.HasValue)\n            return m_IsDesignerHosted.Value;\n        else\n        {\n            if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n            {\n                m_IsDesignerHosted = true;\n                return true;\n            }\n            Control ctrl = this;\n            while (ctrl != null)\n            {\n                if ((ctrl.Site != null) &amp;&amp; ctrl.Site.DesignMode)\n                {\n                    m_IsDesignerHosted = true;\n                    return true;\n                }\n                ctrl = ctrl.Parent;\n            }\n            m_IsDesignerHosted = false;\n            return false;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 54243122, 'author': 'RB Davidson', 'author_id': 113730, 'author_profile': 'https://Stackoverflow.com/users/113730', 'pm_score': 0, 'selected': False, 'text': '<p>I had to fight this problem recently in Visual Studio 2017 when using nested UserControls.  I combine several of the approaches mentioned above and elsewhere, then tweaked the code until I had a decent extension method which works acceptably so far.  It performs a sequence of checks, storing the result in static boolean variables so so each check is only performed at most only once at run time. The process may be overkill, but it is keeping the code from executing in studio. Hope this helps someone.</p>\n\n<pre><code>  public static class DesignTimeHelper\n  {\n    private static bool? _isAssemblyVisualStudio;\n    private static bool? _isLicenseDesignTime;\n    private static bool? _isProcessDevEnv;\n    private static bool? _mIsDesignerHosted; \n\n    /// &lt;summary&gt;\n    ///   Property &lt;see cref="Form.DesignMode"/&gt; does not correctly report if a nested &lt;see cref="UserControl"/&gt;\n    ///   is in design mode.  InDesignMode is a corrected that property which .\n    ///   (see https://connect.microsoft.com/VisualStudio/feedback/details/553305\n    ///   and https://stackoverflow.com/a/2693338/238419 )\n    /// &lt;/summary&gt;\n    public static bool InDesignMode(\n      this Control userControl,\n      string source = null)\n      =&gt; IsLicenseDesignTime\n         || IsProcessDevEnv\n         || IsExecutingAssemblyVisualStudio\n         || IsDesignerHosted(userControl);\n\n    private static bool IsExecutingAssemblyVisualStudio\n      =&gt; _isAssemblyVisualStudio\n         ?? (_isAssemblyVisualStudio = Assembly\n           .GetExecutingAssembly()\n           .Location.Contains(value: "VisualStudio"))\n         .Value;\n\n    private static bool IsLicenseDesignTime\n      =&gt; _isLicenseDesignTime\n         ?? (_isLicenseDesignTime = LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n         .Value;\n\n    private static bool IsDesignerHosted(\n      Control control)\n    {\n      if (_mIsDesignerHosted.HasValue)\n        return _mIsDesignerHosted.Value;\n\n      while (control != null)\n      {\n        if (control.Site?.DesignMode == true)\n        {\n          _mIsDesignerHosted = true;\n          return true;\n        }\n\n        control = control.Parent;\n      }\n\n      _mIsDesignerHosted = false;\n      return false;\n    }\n\n    private static bool IsProcessDevEnv\n      =&gt; _isProcessDevEnv\n         ?? (_isProcessDevEnv = Process.GetCurrentProcess()\n                                  .ProcessName == "devenv")\n         .Value;\n  }\n</code></pre>\n'}, {'answer_id': 70761163, 'author': 'Mike L', 'author_id': 7292047, 'author_profile': 'https://Stackoverflow.com/users/7292047', 'pm_score': 0, 'selected': False, 'text': '<p>I solved this in .NET 5 with the following:</p>\n<pre><code>public static bool InDesignMode()\n{   \n    return Process.GetCurrentProcess().ProcessName.Contains(&quot;DesignToolsServer&quot;);\n}\n</code></pre>\n'}, {'answer_id': 74346003, 'author': 'PhilH', 'author_id': 5714170, 'author_profile': 'https://Stackoverflow.com/users/5714170', 'pm_score': 0, 'selected': False, 'text': '<p>In .Net 6, the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.isancestorsiteindesignmode?f1url=%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(System.Windows.Forms.Control.IsAncestorSiteInDesignMode)%3Bk(DevLang-csharp)%26rd%3Dtrue&amp;view=windowsdesktop-6.0" rel="nofollow noreferrer"><code>Control.IsAncestorSiteInDesignMode</code></a> property is available.</p>\n'}]
['https://Stackoverflow.com/questions/34664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2862/']