If you want to run some lines when it is running but not in the Visual Studio designer, you should implement the DesignMode property as follows:
// this code is in the Load of my UserControl
if (this.DesignMode == false)
{
// This will only run in run time, not in the designer.
this.getUserTypes();
this.getWarehouses();
this.getCompanies();
}
//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
;
}
和许多其他人一样,在设计 Windows 窗体 UserControls 时,我已经多次遇到这个问题。
但是今天,我遇到了这样的情况,上面提到的解决方案对我来说都不管用。
问题是,LicenseManager.UsageMode只能在构造函数中可靠地工作,而 DesignMode只能在构造函数之外工作,而且并不总是这样。这是我的经验,这是什么 is said in a discussion on GitHub。
另一个问题是继承,以及将用户控件嵌入到另一个用户控件中。在最近的第二级嵌入用户控件时,两种方式都失败了!
这可以在我为这个测试创建的用户控件中显示。每个 UC 有3个标签:
它的 (project name)和 type name
的价值观
DesignMode(true: "DM=1") ,
LicenseManager.UsageMode == LicenseUsageMode.Designtime,本地查询(true: “ local _ LM-DT = 1”)
这是我使用 Visual Studio 在 C # 中检查 DesignMode 的技巧,它在构造函数中也可以工作。
// add this class...
public static class Globals
{
static Globals() => DesignMode = true;
public static bool DesignMode { get; set; }
}
// and modify your existing class...
public static class Program
{
public static void Main()
{
Globals.DesignMode = false;
// ...
// ... and then the rest of your program
//
// in any of your code you can check Globals.DesignMode for
// the information you want.
}
}
这个解决方案是轻量级和简单的。缺点是您必须记住清除 Main 代码中的标志。
当检查“设计模式”时,我们实际上是在检查我们的代码是否正在执行,因为我们的整个程序正在运行,或者因为我们的部分代码正在由 VS 设计器执行。使用这个解决方案,只有在整个程序运行时,标志才会设置为 false。