我正在查看一些创建Outlook上下文菜单按钮的示例:
private void Application_ItemContextMenuDisplay(Microsoft.Office.Core.CommandBar CommandBar,
Selection Selection)
{
var button = (Office.CommandBarButton)CommandBar.Controls.
Add(Office.MsoControlType.msoControlButton, missing,
missing, missing, missing);
button.accName = "SowSelectedItem";
button.DescriptionText = "Show Selected item";
button.Caption = button.DescriptionText;
button.Tag = "ShowSelectedItem";
button.Click += ContextMenuItemClicked;
}
这个工作正确一次 - 它在菜单上创建一个按钮就好了,它是可点击的,我的事件处理程序在第一次访问时触发。
但是,菜单激活会反复触发,每次运行时都会添加另一个事件处理程序(但菜单上只显示一个按钮),因此单击该按钮现在会多次触发处理程序 - 每次访问一次之前 - 点击处理程序正在累积(即使我每次都添加一个新按钮)。
好的,所以我想我可以:
我觉得我在这里遗漏了一些东西。如何连接按钮,以便我获得正确的按钮激活,只有一个事件处理程序命中?
答案 0 :(得分:2)
我仍然不太确定Outlook正在对该按钮做什么,但以下代码通过实现菜单激活和取消激活以及在停用时删除事件处理程序来解决问题。
public partial class ContextMenuLookupAddin
{
Outlook.Explorer currentExplorer = null;
CommandBarButton contextButton = null;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
currentExplorer = Application.ActiveExplorer();
Application.ItemContextMenuDisplay += Application_ItemContextMenuDisplay;
Application.ContextMenuClose +=Application_ContextMenuClose;
}
private void Application_ItemContextMenuDisplay(Microsoft.Office.Core.CommandBar CommandBar,
Selection Selection)
{
if (contextButton == null)
{
contextButton = (Office.CommandBarButton)CommandBar.Controls.
Add(Office.MsoControlType.msoControlButton, missing,
missing, missing, missing);
contextButton.accName = "SowSelectedItem";
}
contextButton.DescriptionText = "Show Selected item";
contextButton.Caption = contextButton.DescriptionText;
contextButton.Tag = "ShowSelectedItem";
contextButton.FaceId = 4000;
contextButton.OnAction = "OutlookIntegration.ThisAddIn.ContextMenuItemClicked";
contextButton.Click += ContextMenuItemClicked;
}
private void Application_ContextMenuClose(OlContextMenu ContextMenu)
{
contextButton.Click -= ContextMenuItemClicked;
contextButton.Delete(missing);
contextButton = null;
}
private void ContextMenuItemClicked(CommandBarButton Ctrl, ref bool CancelDefault)
{
if (currentExplorer.Selection.Count > 0)
{
object selObject = currentExplorer.Selection[1];
if (selObject is MailItem)
{
// do your stuff with the selected message here
MailItem mail = selObject as MailItem;
MessageBox.Show("Message Subject: " + mail.Subject);
}
}
}
}