如何检测C#Windows窗体代码是否在Visual Studio中执行?

use*_*291 44 c# winforms

是否有变量或预处理器常量允许知道代码是在Visual Studio的上下文中执行的?

Asa*_*sad 62

根据需要尝试Debugger.IsAttachedDesignMode属性或获取ProcessName或组合

Debugger.IsAttached // or                                       
LicenseUsageMode.Designtime // or 
System.Diagnostics.Process.GetCurrentProcess().ProcessName
Run Code Online (Sandbox Code Playgroud)

这是一个例子

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记Process.GetCurrentProcess()上的疯狂内存泄漏,记得要处理掉 (7认同)

Dig*_*der 17

DesignMode属性并不总是准确的.我们已经使用了这种方法,因此它可以保持一致:

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

            return LicenseManager.UsageMode == LicenseUsageMode.Designtime;
        }
    }
Run Code Online (Sandbox Code Playgroud)

您的通话环境非常重要.如果在某些情况下在事件中运行,我们已经在IDE中返回false.


tan*_*ius 6

DesignMode组件的属性.使用VS的Design Viewer时非常方便.

但是,当您在Visual Studio中讨论调试时,您需要使用该Debugger.IsAttached属性.然后,你可以使用

#if DEBUG
#endif
Run Code Online (Sandbox Code Playgroud)