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;
        }
    }
}

The DesignMode property isn't always accurate. We have had use this method so that it works consistently:

    protected new bool DesignMode
    {
        get
        {
            if (base.DesignMode)
                return true;

            return LicenseManager.UsageMode == LicenseUsageMode.Designtime;
        }
    }

The context of your call is important. We've had DesignMode return false in the IDE if running in an event under certain circumstances.