问题
I have a user control that I'm building. It's purpose is to display the status of a class to the user. Obviously, this does not matter, and will slow things down when the control runs in the IDE, as it does as soon as you add it to a form.
One way to work around this would be to have the control created and added to the controls collection of the form at run-time. But this seems less than perfect.
Is there a way to set a flag in the control so that it can skip certain sections of code based on how it is running?
p.s. I'm using C# and VS 2008
回答1:
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;
}
回答2:
I found this answer on another post and it seems to be easier and working better for my situation.
Detecting design mode from a Control's constructor
using System.ComponentModel;
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
}
回答3:
This is the method I used in my project:
//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
;
}
Attention!!!: The code returned bool is indicating NOT in design mode!
来源:https://stackoverflow.com/questions/336817/how-can-i-detect-whether-a-user-control-is-running-in-the-ide-in-debug-mode-or