<p>I am getting some errors thrown in my code when I open a Windows Forms form in Visual Studio's designer. I would like to branch in my code and perform a different initialization if the form is being opened by designer than if it is being run for real. </p>

<p>How can I determine at run-time if the code is being executed as part of designer opening the form?</p>

[{'answer_id': 73533, 'author': 'Bob King', 'author_id': 6897, 'author_profile': 'https://Stackoverflow.com/users/6897', 'pm_score': 2, 'selected': False, 'text': '<pre><code>System.Diagnostics.Debugger.IsAttached\n</code></pre>\n'}, {'answer_id': 73541, 'author': 'Adrian Anttila', 'author_id': 5988, 'author_profile': 'https://Stackoverflow.com/users/5988', 'pm_score': 1, 'selected': False, 'text': "<p>I'm not sure if running in debug mode counts as real, but an easy way is to include an <code>if</code> statement in your code that checkes for <code>System.Diagnostics.Debugger.IsAttached</code>.</p>\n"}, {'answer_id': 73553, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 2, 'selected': False, 'text': '<p>It\'s hack-ish, but if you\'re using <a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET" rel="nofollow noreferrer">VB.NET</a> and when you\'re running from within Visual Studio <em>My.Application.Deployment.CurrentDeployment</em> will be Nothing, because you haven\'t deployed it yet. I\'m not sure how to check the equivalent value in C#.</p>\n'}, {'answer_id': 73568, 'author': 'Ryan Steckler', 'author_id': 12673, 'author_profile': 'https://Stackoverflow.com/users/12673', 'pm_score': 1, 'selected': False, 'text': "<p>You check the <code>DesignMode</code> property of your control:</p>\n\n<pre><code>if (!DesignMode)\n{\n//Do production runtime stuff\n}\n</code></pre>\n\n<p>Note that this won't work in your constructor because the components haven't been initialized yet.</p>\n"}, {'answer_id': 73582, 'author': 'Akselsson', 'author_id': 8862, 'author_profile': 'https://Stackoverflow.com/users/8862', 'pm_score': 0, 'selected': False, 'text': '<p>If you are in a form or control you can use the DesignMode property:    </p>\n\n<pre><code>if (DesignMode)\n{\n        DesignMode Only stuff\n}\n</code></pre>\n'}, {'answer_id': 73583, 'author': 'Roger Lipscombe', 'author_id': 8446, 'author_profile': 'https://Stackoverflow.com/users/8446', 'pm_score': 7, 'selected': True, 'text': '<p>To find out if you\'re in "design mode":</p>\n\n<ul>\n<li>Windows Forms components (and controls) have a <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.component.designmode.aspx" rel="noreferrer">DesignMode</a> property.</li>\n<li>Windows Presentation Foundation controls should use the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.designerproperties.isindesignmode.aspx" rel="noreferrer">IsInDesignMode</a> attached property.</li>\n</ul>\n'}, {'answer_id': 73619, 'author': 'ShuggyCoUk', 'author_id': 12748, 'author_profile': 'https://Stackoverflow.com/users/12748', 'pm_score': 0, 'selected': False, 'text': '<pre><code>System.ComponentModel.Component.DesignMode == true\n</code></pre>\n'}, {'answer_id': 73659, 'author': 'JohnV', 'author_id': 4589, 'author_profile': 'https://Stackoverflow.com/users/4589', 'pm_score': 4, 'selected': False, 'text': '<p>The Control.DesignMode property is probably what you\'re looking for. It tells you if the control\'s parent is open in the designer. </p>\n\n<p>In most cases it works great, but there are instances where it doesn\'t work as expected. First, it doesn\'t work in the controls constructor. Second, DesignMode is false for "grandchild" controls. For example, DesignMode on controls hosted in a UserControl will return false when the UserControl is hosted in a parent.</p>\n\n<p>There is a pretty easy workaround. It goes something like this:</p>\n\n<pre><code>public bool HostedDesignMode\n{\n  get \n  {\n     Control parent = Parent;\n     while (parent!=null)\n     {\n        if(parent.DesignMode) return true;\n        parent = parent.Parent;\n     }\n     return DesignMode;\n  }\n}\n</code></pre>\n\n<p>I haven\'t tested that code, but it <em>should</em> work.</p>\n'}, {'answer_id': 353089, 'author': 'GWLlosa', 'author_id': 18071, 'author_profile': 'https://Stackoverflow.com/users/18071', 'pm_score': 4, 'selected': False, 'text': '<p>The most reliable approach is:</p>\n\n<pre><code>public bool isInDesignMode\n{\n    get\n    {\n        System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();\n        bool res = process.ProcessName == "devenv";\n        process.Dispose();\n        return res;\n    }\n}\n</code></pre>\n'}, {'answer_id': 353111, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>We use the following code in UserControls and it does the work. Using only DesignMode will not work in your app that uses your custom user controls as pointed out by other members.</p>\n\n<pre><code>    public bool IsDesignerHosted\n    {\n        get { return IsControlDesignerHosted(this); }\n    }\n\n    public bool IsControlDesignerHosted(System.Windows.Forms.Control ctrl)\n    {\n        if (ctrl != null)\n        {\n            if (ctrl.Site != null)\n            {\n                if (ctrl.Site.DesignMode == true)\n                    return true;\n                else\n                {\n                    if (IsControlDesignerHosted(ctrl.Parent))\n                        return true;\n                    else\n                        return false;\n                }\n            }\n            else\n            {\n                if (IsControlDesignerHosted(ctrl.Parent))\n                    return true;\n                else\n                    return false;\n            }\n        }\n        else\n            return false;\n    }\n</code></pre>\n\n<p>Basically the logic above boils down to:</p>\n\n<pre><code>    public bool IsControlDesignerHosted(System.Windows.Forms.Control ctrl)\n    {\n        if (ctrl == null) return false;\n        if (ctrl.Site != null &amp;&amp; ctrl.Site.DesignMode) return true;\n        return IsControlDesignerHosted(ctrl.Parent);\n    }\n</code></pre>\n'}, {'answer_id': 353162, 'author': 'Eyvind', 'author_id': 25746, 'author_profile': 'https://Stackoverflow.com/users/25746', 'pm_score': 0, 'selected': False, 'text': '<p>I found the DesignMode property to be buggy, at least in previous versions of Visual Studio. Hence, I made my own using the following logic:</p>\n\n<pre><code>Process.GetCurrentProcess().ProcessName.ToLower().Trim() == "devenv";\n</code></pre>\n\n<p>Kind of a hack, I know, but it works well.</p>\n'}, {'answer_id': 7801743, 'author': 'Marty', 'author_id': 184630, 'author_profile': 'https://Stackoverflow.com/users/184630', 'pm_score': 4, 'selected': False, 'text': '<p>The most reliable way to do this is to ignore the DesignMode property and use your own flag that gets set on application startup.</p>\n\n<p>Class:</p>\n\n<pre><code>public static class Foo\n{\n    public static bool IsApplicationRunning { get; set; }\n}\n</code></pre>\n\n<p>Program.cs:</p>\n\n<pre><code>[STAThread]\nstatic void Main()\n{\n     Foo.IsApplicationRunning = true;\n     // ... code goes here ...\n}\n</code></pre>\n\n<p>Then just check the flag whever you need it.</p>\n\n<pre><code>if(Foo.IsApplicationRunning)\n{\n    // Do runtime stuff\n}\nelse\n{\n    // Do design time stuff\n}\n</code></pre>\n'}, {'answer_id': 10725662, 'author': 'NET3', 'author_id': 1289709, 'author_profile': 'https://Stackoverflow.com/users/1289709', 'pm_score': 6, 'selected': False, 'text': '<pre class="lang-cs prettyprint-override"><code>if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)\n{\n  // Design time logic\n}\n</code></pre>\n'}, {'answer_id': 11177035, 'author': 'Andy', 'author_id': 1477990, 'author_profile': 'https://Stackoverflow.com/users/1477990', 'pm_score': 1, 'selected': False, 'text': '<p>When running a project, its name is appended with ".vshost".</p>\n\n<p>So, I use this:</p>\n\n<pre><code>    public bool IsInDesignMode\n    {\n        get\n        {\n            Process p = Process.GetCurrentProcess();\n            bool result = false;\n\n            if (p.ProcessName.ToLower().Trim().IndexOf("vshost") != -1)\n                result = true;\n            p.Dispose();\n\n            return result;\n        }\n    }\n</code></pre>\n\n<p>It works for me.</p>\n'}, {'answer_id': 11477586, 'author': 'Bolek', 'author_id': 1524524, 'author_profile': 'https://Stackoverflow.com/users/1524524', 'pm_score': 1, 'selected': False, 'text': '<p>If you created a property that you don\'t need at all at design time, you can use the <strong>DesignerSerializationVisibility</strong> attribute and set it to Hidden. For example:</p>\n\n<pre><code>protected virtual DataGridView GetGrid()\n{\n    throw new NotImplementedException("frmBase.GetGrid()");\n}\n\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic int ColumnCount { get { return GetGrid().Columns.Count; } set { /*Some code*/ } }\n</code></pre>\n\n<p>It stopped my Visual Studio crashing every time I made a change to the form with <code>NotImplementedException()</code> and tried to save. Instead, Visual Studio knows that I don\'t want to serialize this property, so it can skip it. It only displays some weird string in the properties box of the form, but it seems to be safe to ignore.</p>\n\n<p>Please note that this change does not take effect until you rebuild.</p>\n'}, {'answer_id': 12618972, 'author': 'Johny Skovdal', 'author_id': 222134, 'author_profile': 'https://Stackoverflow.com/users/222134', 'pm_score': 3, 'selected': False, 'text': '<p>The devenv approach stopped working in VS2012 as the designer now has its own process. Here is the solution I am currently using <em>(the \'devenv\' part is left there for legacy, but without VS2010 I am not able to test that though)</em>.</p>\n\n<pre><code>private static readonly string[] _designerProcessNames = new[] { "xdesproc", "devenv" };\n\nprivate static bool? _runningFromVisualStudioDesigner = null;\npublic static bool RunningFromVisualStudioDesigner\n{\n  get\n  {\n    if (!_runningFromVisualStudioDesigner.HasValue)\n    {\n      using (System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess())\n      {\n        _runningFromVisualStudioDesigner = _designerProcessNames.Contains(currentProcess.ProcessName.ToLower().Trim());\n      }\n    }\n\n    return _runningFromVisualStudioDesigner.Value;\n  }\n}\n</code></pre>\n'}, {'answer_id': 13894231, 'author': 'Martin', 'author_id': 419427, 'author_profile': 'https://Stackoverflow.com/users/419427', 'pm_score': 2, 'selected': False, 'text': '<pre><code>using (System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess())\n{\n    bool inDesigner = process.ProcessName.ToLower().Trim() == "devenv";\n    return inDesigner;\n}\n</code></pre>\n\n<p>I tried the above code  (added a using statement) and this would fail on some occasions for me. Testing in the constructor of a usercontrol placed directly in a form with the designer loading at startup. But would work in other places.</p>\n\n<p>What worked for me, in all locations is:</p>\n\n<pre><code>private bool isDesignMode()\n{\n    bool bProcCheck = false;\n    using (System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess())\n    {\n        bProcCheck = process.ProcessName.ToLower().Trim() == "devenv";\n    }\n\n    bool bModeCheck = (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime);\n\n    return bProcCheck || DesignMode || bModeCheck;\n}\n</code></pre>\n\n<p>Maybe a bit overkill, but it works, so is good enough for me.</p>\n\n<p>The success in the example noted above is the bModeCheck, so probably the DesignMode is surplus.</p>\n'}, {'answer_id': 15224011, 'author': 'Ali Reza Kalantar', 'author_id': 2132827, 'author_profile': 'https://Stackoverflow.com/users/2132827', 'pm_score': 0, 'selected': False, 'text': '<p>To solve the problem, you can also code as below:</p>\n\n<pre><code>private bool IsUnderDevelopment\n{\n    get\n    {\n        System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();\n        if (process.ProcessName.EndsWith(".vshost")) return true;\n        else return false;\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 15700675, 'author': 'Lozza', 'author_id': 2223846, 'author_profile': 'https://Stackoverflow.com/users/2223846', 'pm_score': -1, 'selected': False, 'text': '<pre><code>    /// &lt;summary&gt;\n    ///  Whether or not we are being run from the Visual Studio IDE\n    /// &lt;/summary&gt;\n    public bool InIDE\n    {\n        get\n        {\n            return Process.GetCurrentProcess().ProcessName.ToLower().Trim().EndsWith("vshost");\n        }\n    }\n</code></pre>\n'}, {'answer_id': 22781355, 'author': 'pintergabor', 'author_id': 3484286, 'author_profile': 'https://Stackoverflow.com/users/3484286', 'pm_score': 2, 'selected': False, 'text': '<pre><code>/// &lt;summary&gt;\n/// Are we in design mode?\n/// &lt;/summary&gt;\n/// &lt;returns&gt;True if in design mode&lt;/returns&gt;\nprivate bool IsDesignMode() {\n    // Ugly hack, but it works in every version\n    return 0 == String.CompareOrdinal(\n        "devenv.exe", 0,\n        Application.ExecutablePath, Application.ExecutablePath.Length - 10, 10);\n}\n</code></pre>\n'}, {'answer_id': 28432133, 'author': 'GeeC', 'author_id': 1287392, 'author_profile': 'https://Stackoverflow.com/users/1287392', 'pm_score': 3, 'selected': False, 'text': '<p>I had the same problem in Visual Studio Express 2013. I tried many of the solutions suggested here but the one that worked for me was <a href="https://stackoverflow.com/a/21054933/1287392">an answer to a different thread</a>, which I will repeat here in case the link is ever broken:</p>\n\n<pre><code>protected static bool IsInDesigner\n{\n    get { return (Assembly.GetEntryAssembly() == null); }\n}\n</code></pre>\n'}, {'answer_id': 29023756, 'author': 'JWP', 'author_id': 1522548, 'author_profile': 'https://Stackoverflow.com/users/1522548', 'pm_score': 0, 'selected': False, 'text': "<p>Here's another one:</p>\n\n<pre><code>        //Caters only to thing done while only in design mode\n        if (App.Current.MainWindow == null){ // in design mode  }\n\n        //Avoids design mode problems\n        if (App.Current.MainWindow != null) { //applicaiton is running }\n</code></pre>\n"}, {'answer_id': 30196577, 'author': 'Gary', 'author_id': 4892369, 'author_profile': 'https://Stackoverflow.com/users/4892369', 'pm_score': -1, 'selected': False, 'text': '<p>Here\'s a flexible way that is adaptable to where you compile from as well as whether or not you care which mode you\'re in.</p>\n\n<pre><code>string testString1 = "\\\\bin\\\\";\n//string testString = "\\\\bin\\\\Debug\\\\";\n//string testString = "\\\\bin\\\\Release\\\\";\n\nif (AppDomain.CurrentDomain.BaseDirectory.Contains(testString))\n{\n    //Your code here\n}\n</code></pre>\n'}, {'answer_id': 36042135, 'author': 'Gpower2', 'author_id': 3235669, 'author_profile': 'https://Stackoverflow.com/users/3235669', 'pm_score': 0, 'selected': False, 'text': '<p>After testing most of the answers here, unfortunately nothing worked for me (VS2015). \nSo I added a little twist to <a href="https://stackoverflow.com/a/73659/3235669">JohnV\'s answer</a>, which didn\'t work out of the box, since DesignMode is a protected Property in the Control class.</p>\n\n<p>First I made an extension method which returns the DesignMode\'s Property value via Reflection:</p>\n\n<pre><code>public static Boolean GetDesignMode(this Control control)\n{\n    BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static;\n    PropertyInfo prop = control.GetType().GetProperty("DesignMode", bindFlags);\n    return (Boolean)prop.GetValue(control, null);\n}\n</code></pre>\n\n<p>and then I made a function like JohnV:</p>\n\n<pre><code>public bool HostedDesignMode\n{\n    get\n    {\n        Control parent = Parent;\n        while (parent != null)\n        {\n            if (parent.GetDesignMode()) return true;\n            parent = parent.Parent;\n        }\n        return DesignMode;\n    }\n}\n</code></pre>\n\n<p>This is the only method that worked for me, avoiding all the ProcessName mess, and while reflection should not be used lightly, in this case it did all the difference! ;)</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>You can also make the second function an extension method like this:</p>\n\n<pre><code>public static Boolean IsInDesignMode(this Control control)\n{\n    Control parent = control.Parent;\n    while (parent != null)\n    {\n        if (parent.GetDesignMode())\n        {\n            return true;\n        }\n        parent = parent.Parent;\n    }\n    return control.GetDesignMode();\n}\n</code></pre>\n'}, {'answer_id': 72997523, 'author': 'NielW', 'author_id': 570206, 'author_profile': 'https://Stackoverflow.com/users/570206', 'pm_score': 0, 'selected': False, 'text': "<p>For WPF (hopefully this is useful for those WPF people stumbling upon this question):</p>\n<pre><code>if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(new DependencyObject()))\n{\n}\n</code></pre>\n<p><code>GetIsInDesignMode</code> requires a DependencyObject. If you don't have one, just create one.</p>\n"}]
['https://Stackoverflow.com/questions/73515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12717/']