Detecting design mode from a Control's constructor

Following-on from this question, is it possible to detect whether one is in design or runtime mode from within an object's constructor?

I realise that this may not be possible, and that I'll have to change what I want, but for now I'm interested in this specific question.


Solution 1:

You can use the LicenceUsageMode enumeration in the System.ComponentModel namespace:

bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);

Solution 2:

Are you looking for something like this:

public static bool IsInDesignMode()
{
    if (Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) > -1)
    {
        return true;
    }
    return false;
}

You can also do it by checking process name:

if (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv")
   return true;

Solution 3:

Component ... as far as I know does not have the DesignMode property. This property is provided by Control. But the problem is when CustomControl is located in a Form in the designer, this CustomControl is running in runtime mode.

I have experienced that the DesignMode property works correct only in Form.

Solution 4:

Controls(Forms, UserControls etc.) inherit Component class which has bool property DesignMode so:

if(DesignMode)
{
  //If in design mode
}

Solution 5:

IMPORTANT

There is a difference of using Windows Forms or WPF!!

They have different designers and and need different checks. Additionally it's tricky when you mix Forms and WPF controls. (e.g. WPF controls inside of a Forms window)

If you have Windows Forms only, use this:

Boolean isInWpfDesignerMode   = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);

If you have WPF only, use this check:

Boolean isInFormsDesignerMode = (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv");

If you have mixed usage of Forms and WPF, use a check like this:

Boolean isInWpfDesignerMode   = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
Boolean isInFormsDesignerMode = (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv");

if (isInWpfDesignerMode || isInFormsDesignerMode)
{
    // is in any designer mode
}
else
{
    // not in designer mode
}

To see the current mode you can show a MessageBox for debugging:

// show current mode
MessageBox.Show(String.Format("DESIGNER CHECK:  WPF = {0}   Forms = {1}", isInWpfDesignerMode, isInFormsDesignerMode));

Remark:

You need to add the namespaces System.ComponentModel and System.Diagnostics.