如何检测用户控件是在IDE中,在调试模式下还是在已发布的EXE中运行?

我有一个用户控件,我正在构建。 它的目的是向用户显示类的状态。 显然,这并不重要,并且当控件在IDE中运行时会降低速度,就像将其添加到表单中一样。

解决此问题的一种方法是在运行时创建控件并将其添加到窗体的控件集合中。 但这似乎并不完美。

有没有办法在控件中设置一个标志,以便它可以根据它的运行方式跳过某些代码段?

ps我正在使用C#和VS 2008

public static bool IsInRuntimeMode( IComponent component ) { bool ret = IsInDesignMode( component ); return !ret; } public static bool IsInDesignMode( IComponent component ) { bool ret = false; if ( null != component ) { ISite site = component.Site; if ( null != site ) { ret = site.DesignMode; } else if ( component is System.Windows.Forms.Control ) { IComponent parent = ( (System.Windows.Forms.Control)component ).Parent; ret = IsInDesignMode( parent ); } } return ret; } 

我在另一篇文章中找到了这个答案,它似乎更容易,并且对我的情况更好。

从Control的构造函数中检测设计模式

 using System.ComponentModel; if (LicenseManager.UsageMode == LicenseUsageMode.Runtime) { } 

这是我在项目中使用的方法:

 //use a Property or Field for keeping the info to avoid runtime computation public static bool NotInDesignMode { get; } = IsNotInDesignMode(); private static bool IsNotInDesignMode() { /* File.WriteAllLines(@"D:\1.log", new[] { LicenseManager.UsageMode.ToString(), //not always reliable, eg WPF app in Blend this will return RunTime Process.GetCurrentProcess().ProcessName, //filename without extension Process.GetCurrentProcess().MainModule.FileName, //full path Process.GetCurrentProcess().MainModule.ModuleName, //filename Assembly.GetEntryAssembly()?.Location, //null for WinForms app in VS IDE Assembly.GetEntryAssembly()?.ToString(), //null for WinForms app in VS IDE Assembly.GetExecutingAssembly().Location, //always return your project's output assembly info Assembly.GetExecutingAssembly().ToString(), //always return your project's output assembly info }); //*/ //LicenseManager.UsageMode will return RunTime if LicenseManager.context is not present. //So you can not return true by judging it's value is RunTime. if (LicenseUsageMode.Designtime == LicenseManager.UsageMode) return false; var procName = Process.GetCurrentProcess().ProcessName.ToLower(); return "devenv" != procName //WinForms app in VS IDE && "xdesproc" != procName //WPF app in VS IDE/Blend && "blend" != procName //WinForms app in Blend //other IDE's process name if you detected by log from above ; } 

注意!!!:返回bool的代码表示不在设计模式下!