visual-studioadd-inenvdteform-designer

Updating form designer after adding controls through an Add-In


I am exploring the EnvDTE library, and building a form generator.

I have successfully added controls to a form, however, the controls' codes are not added to the form designer (formname.Designer.cs), and that is a problem if I want to add event handlers, because the controls are not yet declared.

When I double-click a button, which adds the event handler to the button in the form designer, that adds all of the controls in the form designer. So any update should do it.

Here's how I'm adding the controls:

//this ProjectItem (itemFrom) is a reference to a recently added form,
//and its only window is my form

Window myWindow = itemForm.Document.Windows.Item(1);

IDesignerHost myDesigner = (IDesignerHost)myWindow.Object;

IComponent comp = myDesigner.CreateComponent(typeof(Button), "MyNewButton);

Question: How do I programmatically update the form designer (with EnvDte or VS API) in order to get references to my controls and adding event handlers to them ?

One thing that's weird: I've found a couple of tutorials on adding controls to forms through VS Add-Ins, but none of them has mentioned this problem..


Solution

  • I have found the answer to my questions, but I'm still struggling with some colateral issues of it:

    IEventBindingService myIEventBindingService = (IEventBindingService)myDesigner.GetService(typeof(IEventBindingService));
    myIEventBindingService.ShowCode();
    //obs: myDesigner is of type IDesignerHost
    

    The colateral issues:

    1) The code is actually shown to the user. Which is not desired.
    2) You cannot run it more than once.

    The reason you'd want to run it more than once, is that this update is necessary in order to be able to actually add code to the event handlers, as they cannot be found unless the designer is updated. This means that every piece of code has to be added after every event handler has been added. So no simple methods to add them.

    This way I had to add all the event handlers, update the designer, get references to event handlers through their names and just then write whatever they do.

    I'm eventually going to fix this (EnvDTE is poorly documented), and then I'll update this answer.