Zvi*_*Zvi 55 gui-designer visual-studio
当我在Visual Studio的设计器中打开Windows窗体表单时,我的代码中出现了一些错误.我希望在我的代码中进行分支,如果表单由设计者打开,则执行不同的初始化,而不是实际运行.
如何在运行时确定代码是否作为设计人员打开表单的一部分执行?
Rog*_*mbe 49
要了解您是否处于"设计模式":
NET*_*ET3 48
if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)
{
// Design time logic
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*hnV 19
Control.DesignMode属性可能就是您要查找的内容.它告诉您控件的父级是否在设计器中打开.
在大多数情况下,它运行良好,但有些情况下它不能按预期工作.首先,它在控件构造函数中不起作用.其次,DesignMode对于"孙子"控件是错误的.例如,当UserControl托管在父对象中时,UserControl中托管的控件上的DesignMode将返回false.
有一个非常简单的解决方法.它是这样的:
public bool HostedDesignMode
{
get
{
Control parent = Parent;
while (parent!=null)
{
if(parent.DesignMode) return true;
parent = parent.Parent;
}
return DesignMode;
}
}
Run Code Online (Sandbox Code Playgroud)
我没有测试过该代码,但它应该可以工作.
GWL*_*osa 15
最可靠的方法是:
public bool isInDesignMode
{
get
{
System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
bool res = process.ProcessName == "devenv";
process.Dispose();
return res;
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ill 13
最可靠的方法是忽略DesignMode属性并使用在应用程序启动时设置的自己的标志.
类:
public static class Foo
{
public static bool IsApplicationRunning { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Program.cs中:
[STAThread]
static void Main()
{
Foo.IsApplicationRunning = true;
// ... code goes here ...
}
Run Code Online (Sandbox Code Playgroud)
然后只需检查您需要的标志.
if(Foo.IsApplicationRunning)
{
// Do runtime stuff
}
else
{
// Do design time stuff
}
Run Code Online (Sandbox Code Playgroud)
我在 Visual Studio Express 2013 中遇到了同样的问题。我尝试了这里建议的许多解决方案,但对我有用的解决方案是对不同线程的回答,如果链接断开,我将在此处重复:
protected static bool IsInDesigner
{
get { return (Assembly.GetEntryAssembly() == null); }
}
Run Code Online (Sandbox Code Playgroud)
devenv方法在VS2012停止工作,因为设计师现在有自己的流程.这是我目前正在使用的解决方案('devenv'部分留在那里用于遗留,但没有VS2010,我无法测试它).
private static readonly string[] _designerProcessNames = new[] { "xdesproc", "devenv" };
private static bool? _runningFromVisualStudioDesigner = null;
public static bool RunningFromVisualStudioDesigner
{
get
{
if (!_runningFromVisualStudioDesigner.HasValue)
{
using (System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess())
{
_runningFromVisualStudioDesigner = _designerProcessNames.Contains(currentProcess.ProcessName.ToLower().Trim());
}
}
return _runningFromVisualStudioDesigner.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39959 次 |
| 最近记录: |