How to tell if .NET code is being run by Visual Studio designer

To find out if you're in "design mode":

  • Windows Forms components (and controls) have a DesignMode property.
  • Windows Presentation Foundation controls should use the IsInDesignMode attached property.

if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)
{
  // Design time logic
}

The Control.DesignMode property is probably what you're looking for. It tells you if the control's parent is open in the designer.

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.

There is a pretty easy workaround. It goes something like this:

public bool HostedDesignMode
{
  get 
  {
     Control parent = Parent;
     while (parent!=null)
     {
        if(parent.DesignMode) return true;
        parent = parent.Parent;
     }
     return DesignMode;
  }
}

I haven't tested that code, but it should work.


The most reliable approach is:

public bool isInDesignMode
{
    get
    {
        System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
        bool res = process.ProcessName == "devenv";
        process.Dispose();
        return res;
    }
}

The most reliable way to do this is to ignore the DesignMode property and use your own flag that gets set on application startup.

Class:

public static class Foo
{
    public static bool IsApplicationRunning { get; set; }
}

Program.cs:

[STAThread]
static void Main()
{
     Foo.IsApplicationRunning = true;
     // ... code goes here ...
}

Then just check the flag whever you need it.

if(Foo.IsApplicationRunning)
{
    // Do runtime stuff
}
else
{
    // Do design time stuff
}