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

后端 未结 8 1939
春和景丽
春和景丽 2020-11-29 23:46

Is there a variable or a preprocessor constant that allows to know that the code is executed within the context of Visual Studio?

8条回答
  •  感情败类
    2020-11-30 00:30

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

提交回复
热议问题