2013-06-25 2 views
7

Можно ли отключить или настроить контекстное меню (ячейка, диапазон) через 0 (0) через C# (VSTO). Если да, то как я могу реализовать (в уровне документа приложения в VSTO Excel)VSTO (уровень документа): индивидуальное контекстное меню в Excel (меню правой кнопки мыши)

Например, я хочу, чтобы отключить некоторые пункты в контекстном меню (например, копирование/вставка) и добавить новые элементы или заменить стандартное контекстное меню с полным собственным меню!

Smarttags хорошая альтернатива контекстным меню в Excel?

+1

Да, это возможно с Globals.ThisWorkbook.Application.Commandbars. Я не сделал этого некоторое время, но это должно заставить вас начать. – rwisch45

ответ

11
  • Вот некоторые грубые примеры кода с комментариями
  • Это была создана в VS2010 и испытаны против Excel 2010
  • Первый шаг был создан новый Excel 2010 Add-In проекта
  • Затем добавлен пример кода ниже кода, созданного внутри ThisAddin.cs.
  • Этот код добавит новый пункт меню и удалит пункты меню вырезания/копирования/вставки при щелчке правой кнопкой мыши по одной ячейке, содержащей «abc». Это должно имитировать изменение контекстного меню на основе содержимого ячейки.
 


    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Xml.Linq; 
    using Excel = Microsoft.Office.Interop.Excel; 
    using Office = Microsoft.Office.Core; 
    using Microsoft.Office.Tools.Excel; 
    using System.Diagnostics; 
    using Microsoft.Office.Interop.Excel; 

    namespace Excel_Menu 
    { 
     public partial class ThisAddIn 
     { 
      private void ThisAddIn_Startup(object sender, System.EventArgs e) 
      { 
       ResetCellMenu(); // reset the cell context menu back to the default 

       // Call this function is the user right clicks on a cell 
       this.Application.SheetBeforeRightClick+=new Excel.AppEvents_SheetBeforeRightClickEventHandler(Application_SheetBeforeRightClick); 
      } 

      private void ThisAddIn_Shutdown(object sender, System.EventArgs e) 
      { 
      } 

      private Office.CommandBar GetCellContextMenu() 
      { 
       return this.Application.CommandBars["Cell"]; 
      } 

      private void ResetCellMenu() 
      { 
       GetCellContextMenu().Reset(); // reset the cell context menu back to the default 
      } 

      private void Application_SheetBeforeRightClick(object Sh, Range Target, ref bool Cancel) 
      { 
       ResetCellMenu(); // reset the cell context menu back to the default 

       if (Target.Cells.Count == 1) // sample code: if only a single cell is selected 
       { 
        if (Target.Cells[1, 1].Value == "abc") // sample code: if the signle cell contains 'abc' 
        { 
         AddExampleMenuItem(); 
         RemoveCutCopyPasteMenuItems(); 
        } 
       } 
      } 

      private void AddExampleMenuItem() 
      { 
       Office.MsoControlType menuItem = Office.MsoControlType.msoControlButton; 
       Office.CommandBarButton exampleMenuItem = (Office.CommandBarButton)GetCellContextMenu().Controls.Add(menuItem, missing, missing, 1, true); 

       exampleMenuItem.Style = Office.MsoButtonStyle.msoButtonCaption; 
       exampleMenuItem.Caption = "Example Menu Item"; 
       exampleMenuItem.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(exampleMenuItemClick); 
      } 

      private void RemoveCutCopyPasteMenuItems() 
      { 
       Office.CommandBar contextMenu = GetCellContextMenu(); 

       for (int i = contextMenu.Controls.Count; i > 0; i--) 
       { 
        Office.CommandBarControl control = contextMenu.Controls[i]; 

        if (control.Caption == "Cu&t") control.Delete(); // Sample code: remove cut menu item 
        else if (control.Caption == "&Copy") control.Delete(); // Sample code: remove copy menu item 
        else if (control.accDescription.Contains("Paste")) control.Delete(); // Sample code: remove any paste menu items 
       } 
      } 

      void exampleMenuItemClick(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault) 
      { 
       System.Windows.Forms.MessageBox.Show("Example Menu Item clicked"); 
      } 

      #region VSTO generated code 

      /// 
      /// Required method for Designer support - do not modify 
      /// the contents of this method with the code editor. 
      /// 
      private void InternalStartup() 
      { 
       this.Startup += new System.EventHandler(ThisAddIn_Startup); 
       this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); 
      } 

      #endregion 
     } 
    } 

 
+0

Спасибо. Но это решение для проекта VSTO Add-In/Application-Level. Мне нужно решение для приложения Document-Level! –

+0

Я еще не создал надстройку уровня документа, но я только что создал новую рабочую книгу Excel 2010. Соответствует ли это тому, как вы его используете? Я смог использовать код сверху в ThisWorkbook.cs, и он работал так же. –