2

According to learn.microsoft.com, I'm trying to get my form's IDesignerHost in design time:

private static Form _findForm;
protected override void OnCreateControl()
{
    if (_findForm == null) { _findForm = FindForm(); }
    if (_findForm == null) { throw new Exception("FindForm() returns null."); }

    // NullReference
    //IDesignerHost dh = (IDesignerHost)_findForm.Site.GetService(typeof(IDesignerHost));
    IDesignerHost dh = (IDesignerHost)GetService(typeof(IDesignerHost));
    Console.WriteLine(dh == null); // true
    // ...
}

But as you see I can't get a ref. Do I need a ": IDesigner" class or is the OnCreateControl call to early to get a valid reference?

Update: About the link in comments:

public override ISite Site
{
    get { return base.Site; }
    set
    {
        Console.WriteLine("Site set"); // Never happens
        base.Site = value;
        if (value == null) { return; }
    }
}

and

Console.WriteLine(Site == null); // true

I tried also events after everything is initialized. Nothing seems to help/work.

So how the heck I can get the IDesignerHost?

7three
  • 163
  • 13

1 Answers1

0

Final Update:

The accepted solution of the question is totally the opposite and wrong:

public override ISite Site
{
    get { return base.Site; }
    set
    {
        base.Site = value;
        if (value == null) { return; }
        IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost;
        if (host != null)
        {
            IComponent componentHost = host.RootComponent;
            if (componentHost is ContainerControl) { ContainerControl = componentHost as ContainerControl; }
        }
    }
}

It should be the getter like this:

private IDesignerHost _host;
public override ISite Site
{
    get
    {
        if (base.Site != null)
        {
            IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
            if (host != null) { _host = host; }
        }
        return base.Site;
    }
    set { base.Site = value; }
}

As I found out, the getter is triggered until it can finally create a valid reference.

base.Site //null
base.Site //null
base.Site //null
base.Site //null
base.Site //...
base.Site //finally got a reference - time to grab it! ;)
7three
  • 163
  • 13