How to detect that C# Windows Forms code is executed within Visual Studio?

Try Debugger.IsAttached or DesignMode property or get ProcessName or a combination, as appropriate

Debugger.IsAttached // or                                       
LicenseUsageMode.Designtime // or 
System.Diagnostics.Process.GetCurrentProcess().ProcessName

Here is a sample

public static class DesignTimeHelper {
    public static bool IsInDesignMode {
        get {
            bool isInDesignMode = LicenseManager.UsageMode == LicenseUsageMode.Designtime || Debugger.IsAttached == true;

            if (!isInDesignMode) {
                using (var process = Process.GetCurrentProcess()) {
                    return process.ProcessName.ToLowerInvariant().Contains("devenv");
                }
            }

            return isInDesignMode;
        }
    }
}

Leave a Comment