问题
This has already been asked here, but I am just not satisfied with the answer given.
I am currently adding a custom context menu to Outlook. The code is as follows:
void Application_ItemContextMenuDisplay(Microsoft.Office.Core.CommandBar CommandBar, Microsoft.Office.Interop.Outlook.Selection Selection)
{
if (Online)
{
foreach (string category in FilingRuleManager.FilingRuleCategories)
{
Office.CommandBarPopup cb = CommandBar.Controls.Add(Office.MsoControlType.msoControlPopup, missing, missing, missing, true) as Office.CommandBarPopup;
cb.BeginGroup = true;
cb.Visible = true;
cb.Tag = MENUNAME;
cb.Caption = category;
//now add the filing rules as a sub menu
foreach (FilingRuleDB rule in FilingRuleManager.FilingRules.Values)
{
if (rule.RuleCategory == category)
{
Office.CommandBarButton cbSub = cb.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing, true) as Office.CommandBarButton;
_FilingRules.Add(cbSub);
cbSub.Visible = true;
cbSub.Caption = rule.RuleName;
cbSub.Tag = rule.FilingRuleID.ToString();
cbSub.Click += new Office._CommandBarButtonEvents_ClickEventHandler(FilingRules_Click);
}
}
}
}
}
When i run the application, each time i show the context menu in Outlook the Click handler (FilingRules_Click) is fired that many times. So if i right click 3 times, the handler is executed 3 times and so on.
There must be a better way to acheive this than the hack in the question linked above.
I have tried:
- Removing the CommandBarButtons just before adding them - however they do not exist!! as every time the Outlook Context menu is hidden, the custom items are automatically removed.
- Storing the controls in a List and then attempting to remove the handlers - this gives an AV as the buttons no longer exist after the menu is hidden.
- There is no ItemContextMenuHidden() event for me to hook into otherwise i would have tried that.
- Adding the items when the Add-in starts (i.e. only once with no ItemContextMenuDisplay() handler), however the items never appear due to the fact that they always get cleared when the menu is shown.
Anyone out there have another suggestion?
回答1:
Solved the problem.
- define the commandbutton as class level static variable
attachment event
ContextMenuClose
forOutlook.Application
.outlookInstance.ContextMenuClose += new ApplicationEvents_11_ContextMenuCloseEventHandler(outlookInstance_ContextMenuClose);
implement the method as code
void outlookInstance_ContextMenuClose(OlContextMenu ContextMenu) { if (ContextMenu == OlContextMenu.olItemContextMenu) { ContextIndexButton.Click -= new _CommandBarButtonEvents_ClickEventHandler(<your method>); ContextIndexButton = null; } }
来源:https://stackoverflow.com/questions/9272747/outlook-context-menu-item-click-fired-multiple-times