We setup a custom context menu when you right click an email in Outlook like so:
private void _application_ItemContextMenuDisplay(Office.CommandBar CommandBar, Interop.Selection Selection)
{
var contextButton = (Office.CommandBarButton)CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, Temporary: true);
contextButton.Visible = true;
contextButton.Caption = "&My Context Menu";
contextButton.Click += MyContextMenu_Click;
}
This method is subscribed to Application.ItemContextMenuDisplay.
It’s working fine, except that occasionally our event gets fired multiple times. It happens when you right-click quickly on different emails.
Then it makes me wonder, when is a good place to cleanup my temporary context menu item? I need to unsubscribe the C# event somewhere. Where is the intended place to do that? (I would also think we might need to call Marshal.ReleaseComObject)
We are using VSTO and the Outlook 2010 project template in Visual Studio. I haven’t found many good examples of customizing the context menu, in general.
This quirkiness is probably why in Outlook 2010, Microsoft is moving more towards the Ribbon XML context menu customizations in favor of the Outlook 2007-style of
CommandBars. See related SO post.As for cleaning up resources used by the
CommandBars, you would need to attach to theApplication.ContextMenuCloseevent to free up resources and unsubscribe your listener. See related SO post on disposing Outlook Context Menus.You should refactor your code to utilize the newer Ribbon XML interface to avoid
CommandBars.