问题:在开始呈现窗体/控件之前,是否可以在WinForms设计器启动时运行一些初始化代码?我通常会在Program.cs的入口点做一些事情。
我的具体情况:
我有一个控制容器的反转(我使用的是SimpleInjector),当我的程序运行时,我会引导它。我在Program.cs的入口点之后立即这样做:
Container.Register<IDockingManager, DockingManagerImpl>(Lifestyle.Singleton);在我的控件的构造函数或Load事件处理程序中,我使用容器获取某些对象的实例:
DockingManager = IOCC.Container.GetInstance<IDockingManager>();如果没有在接口中注册具体的实现,这是行不通的。通常,它会在入口点注册,但设计器不会在Program.cs中运行代码。结果是,由于异常,设计器无法呈现我的控件:
无法找到IDockingManager类型的注册。请注意,您正在解析的容器实例不包含注册。会不会是您意外地创建了一个新的-and空容器?
我当前的黑客解决方案:
在静态构造函数中,我正在检查进程名,以查看Visual是否正在运行我的代码。如果是的话,我假设代码是由设计器运行的,并且运行我的初始化代码。我还必须检查我的容器是否已经初始化了,因为出于某种原因,设计人员可以多次运行静态构造函数,同时保持类的静态状态(这是一个bug吗?)
static IOCC()
{
if(Initialized)
{
return;
}
Container = new Container();
if (IsInDesignMode())
{
RegisterTypes();
}
Initialized = true;
}
private static bool Initialized { get; }
public static Container Container { get; }
private static bool IsInDesignMode()
{
using (var process = Process.GetCurrentProcess())
{
return process.ProcessName == "devenv";
}
}
public static void RegisterTypes()
{
Container.Register<IDockingManager, DockingManagerImpl>(Lifestyle.Singleton);
// ...
}这感觉很烦人,甚至不总是起作用。静态构造函数有时由于某种原因不运行,为了修复它,我必须重新构建我的项目。是否有更好的方法为设计器运行初始化代码?
发布于 2017-03-14 11:13:57
我希望我能正确理解你想要的:
这些函数停止了GUI的呈现。这就是你想要的吗?
[DllImport("user32.dll", EntryPoint = "SendMessageA", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
private const int WM_SETREDRAW = 0xB;
public static void SuspendDrawing(this Control target)
{
SendMessage(target.Handle, WM_SETREDRAW, 0, 0);
}
public static void ResumeDrawing(this Control target) { ResumeDrawing(target, true); }
public static void ResumeDrawing(this Control target, bool redraw)
{
SendMessage(target.Handle, WM_SETREDRAW, 1, 0);
if (redraw)
{
target.Refresh();
}
}用法:
cstrctor()
{
//Designer is the static class which holdes these funcs
Designer.SuspendDrawing(this);
//run some code here
Designer.ResumeDrawing(this);
}https://stackoverflow.com/questions/42784327
复制相似问题