我正在构建一个用户控件。它的目的是向用户显示类的状态。显然,这并不重要,并且当控件在IDE中运行时会减慢速度,就像将其添加到表单中一样。
解决此问题的一种方法是在运行时创建控件并将其添加到窗体的控件集合中。但这似乎并不完美。
有没有办法在控件中设置一个标志,以便它可以根据它的运行方式跳过某些代码段?
P.S。我正在使用C#和VS 2008
答案 0 :(得分:15)
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;
}
答案 1 :(得分:4)
我在另一篇文章中找到了这个答案,它似乎更容易,并且对我的情况更有效。
Detecting design mode from a Control's constructor
using System.ComponentModel;
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
}
答案 2 :(得分:0)
这是我在项目中使用的方法:
//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, e.g. 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代码指示否!