Dervall
Dervall

Reputation: 5744

Visual studio add in context menu does not receive events

I'm experimenting with a visual studio addon and have come across very odd behaviour. I'm adding a right click context menu item and I'm not getting the events to fire unless I put a breakpoint in the OnConnect method and wait a little while. I'm doing pretty much exactly as in this article.

It's a totally standard add-in with this code:

public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
    applicationObject = (DTE2)application;
    addInInstance = (AddIn)addInInst;

    var commandBars = ((CommandBars)applicationObject.CommandBars)["Code Window"];
    var popup = commandBars.Controls.Add(MsoControlType.msoControlButton,
                System.Reflection.Missing.Value, 
                System.Reflection.Missing.Value, 1, true);
    popup.Caption = "View graph";
    var commandBarEvents = (CommandBarEvents)(applicationObject.Events.CommandBarEvents[popup]);
    commandBarEvents.Click += ViewGraphClick;
}

private void ViewGraphClick(object commandbarcontrol, ref bool handled, ref bool canceldefault)
{
    var selection = (TextSelection)applicationObject.ActiveDocument.Selection;
    selection.Insert("Hello, world!");
    handled = true;
}

If I wait with a breakpoint early in the method, this addon will work. If I don't wait it will never call my event. It will however add my item to the context menu in all cases.

As far as I can see this method only gets called once. Any ideas on what I'm doing wrong here?

Update: I've tried to put the same initialization code in OnStartup. The result is the same. I've also tried to do as per the example shown here, but my OnConnection only gets called once with the connectMode set to Startup.

Update 2 I've tried as many combinations of this as possible, moving all the initialization around. Eventually, I gave up and started using another example which uses commands instead of plain context menus. This is probably a better solution in the long run, but I'm still interested in why the original code didn't work.

Upvotes: 0

Views: 763

Answers (1)

Uveper
Uveper

Reputation: 36

Make these variables global:

    CommandBarEvents commandBarEvents;
    CommandBar commandBars;
    CommandBarControl popup;

If you create these objects in OnConnection, they are disposed as soon as the code goes out of scope.

Upvotes: 2

Related Questions