如何在WinForms设计器呈现我的控件之前运行初始化代码?

时间:2017-03-14 11:07:39

标签: c# .net winforms initialization

问题:在开始渲染表单/控件之前,有没有办法在WinForms设计器启动时运行一些初始化代码?我通常在Program.cs的入口点做的事情。

我的具体情况:

我有一个控制容器的反转,(我正在使用SimpleInjector),当我的程序运行时我会引导它。我在Program.cs的入口点后立即执行此操作:

Container.Register<IDockingManager, DockingManagerImpl>(Lifestyle.Singleton);

在我的一些控件的构造函数或Load事件处理程序中,我使用容器来获取某些对象的实例:

DockingManager = IOCC.Container.GetInstance<IDockingManager>();

如果未在接口中注册具体实现,则此操作无效。通常它会在入口点注册,但设计者不会在Program.cs中运行代码。结果是设计器由于异常而无法呈现我的控件:

  

无法找到IDockingManager类型的注册。请注意,您要解析的容器实例不包含注册。难道你不小心创建了一个新的 - 空容器吗?

我目前的hacky解决方案:

在静态构造函数中,我正在检查进程名称以查看Visual Studio是否正在运行我的代码。如果是,我假设代码是由设计者运行的,我运行我的初始化代码。我还必须检查我的容器是否已经初始化,因为设计器由于某种原因可以多次运行静态构造函数,同时保持类的静态状态(这是一个错误吗?)

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);
    // ...
}

这感觉非常hacky,甚至不能一直工作。由于某种原因,静态构造函数有时不运行,为了修复它,我必须重建我的项目。有没有更好的方法来为设计师运行初始化代码?

1 个答案:

答案 0 :(得分:0)

我希望我能正确理解你想要的东西:

这些功能停止渲染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);
}