Visio 2007 add-in menu click handler goes away (C#)

T

travis_

Hi all,

This is my first office add-in so apologies for a novice question.

I am attempting to add a custom menu / menuItem (with an associated click
handler) to the standard Visio menu. The click hander works correctly on
invocations until I load a document. At that point, the menu items are still
presently but the click handler is not invoked.

My suspicion is that the garbage collector is collecting the handler (for
some reason).

Any suggestions? Thanks in advance.

Here is the relevant snippet:

public void OnConnection(object application,
Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array
custom)
{
vsoApplication =
(Microsoft.Office.Interop.Visio.Application)application;
addInInstance = addInInst;

CommandBarPopup popup = AddMenuToMenuBar(vsoApplication,
"VisioTest");
CommandBarButton menuItem = AddMenuItemToMenuBar(popup,
"MenuItem...");
menuItem.Click += new
_CommandBarButtonEvents_ClickEventHandler(MenuItem_Click);
}

private void MenuItem_Click(CommandBarButton control, ref bool
cancelDefault)
{
Trace.WriteLine("MenuItem clicked");
}

public static CommandBarButton AddMenuItemToMenuBar(CommandBarPopup
menuPopup, string menuItemCaption)
{
if (menuPopup == null) return null;

try
{
CommandBarButton menuItem =
(CommandBarButton)menuPopup.Controls.Add(MsoControlType.msoControlButton, 1,
"", 1, true);
menuItem.Caption = menuItemCaption;
menuItem.Style = MsoButtonStyle.msoButtonCaption;
menuItem.Visible = true;
return menuItem;
}
catch (Exception err)
{
Debug.WriteLine(err.Message);
throw;
}
}

public static CommandBarPopup
AddMenuToMenuBar(Microsoft.Office.Interop.Visio.Application application,
string caption)
{
if (application == null) return null;

try
{
CommandBars applicationCommandBars =
(CommandBars)application.CommandBars;
CommandBar menuBar = applicationCommandBars.ActiveMenuBar;

// Add a pop-up menu to the end of the active menu bar.
CommandBarPopup menuPopup =
(CommandBarPopup)menuBar.Controls.Add(MsoControlType.msoControlPopup, 1, "",
10, true);
menuPopup.Caption = caption;
return menuPopup;
}
catch (Exception err)
{
Debug.WriteLine(err.Message);
throw;
}
}
 
T

travis_

Never mind. Answered my own question.

The following works:
1) Move CommandBarPopup & CommandBarButton to class scope
2) Add an entry for the Tag member of the menuItem (menuItem.Tag =
"sometag";). Saw this in another post on this newsgroup.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top