2012-08-30 179 views
1
創建命令按鈕

我看的一定數量的創建這樣的Outlook上下文菜單按鈕的例子:在Outlook 2010 VSTO

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; 
    } 

只能用一次正確的 - 它創建的菜單就好上的按鈕它是可點擊的,我的事件處理程序在第一次訪問時觸發。

但是,菜單激活反覆觸發,每次運行時它似乎都會添加一個事件處理程序(但菜單上只顯示一個按鈕),因此單擊該按鈕現在會多次觸發處理程序 - 每次訪問一次之前做過的 - 點擊處理程序正在積累(即使我每次都添加一個新按鈕)。

好了,我想我可以:

  • 設置一個標誌,並且只加載一次按鈕(不顯示在隨後的激活)
  • 緩存按鈕,每次添加它(也沒有按「T展示在後續激活)
  • 緩存,使按鈕可見,每次啓用(不顯示)

我覺得我失去了一些東西。如何連接按鈕,以便正確激活按鈕,並且只有一個事件處理程序被擊中?

回答

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); 
      } 
     } 
    } 
}