从Application.CommandBars 中删除CommandBarButtons不是从ThisAddIn_Shutdown事件上的所有打开的工作簿中删除它们

我有一个.NET 4.0的C#VSTO应用程序,它在Globals.ThisAddIn.Application.CommandBars [“Cell”]上下文菜单中使用了两个自定义的CommandBarButton。 我在ThisAddIn_Startup事件上创build了一次button,它们对于所有的工作簿都非常有用。 如果在不closuresExcel的情况下closures了我的插件,那么如果有多个打开的工作簿,则会出现问题。 只有活动工作簿的右键单击上下文菜单中的button被删除。

代码:

public partial class ThisAddIn { private const string TAG_PASTE_EVENT = "PASTE EVENT"; private const string TAG_COPY_EVENT = "COPY EVENT"; private Office.CommandBarButton copy_event, paste_event; private void ThisAddIn_Startup(object sender, System.EventArgs e) { try { DefineShortcutMenu(); /* * Other start up stuff that works fine */ } catch (Exception ex) { ExceptionHandler.HandleException(ex); } } private void ThisAddIn_Shutdown(object sender, System.EventArgs e) { /* * Other shut down stuff that works fine */ // Remove the right click menu buttons foreach (Office.CommandBarControl control in Application.CommandBars["Cell"].Controls) { if (control.Tag.Equals(TAG_PASTE_EVENT)) { control.Delete(true); } else if (control.Tag.Equals(TAG_COPY_EVENT)) { control.Delete(true); } } } private void copy_event_Click(Office.CommandBarButton Ctrl, ref bool CancelDefault) { // Copy code } private void paste_event_Click(Office.CommandBarButton Ctrl, ref bool CancelDefault) { // Paste code } private void DefineShortcutMenu() { // Create and add the paste button paste_event = (Office.CommandBarButton)Application.CommandBars["Cell"].Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, 1, true); paste_event.Style = Office.MsoButtonStyle.msoButtonCaption; paste_event.Caption = "Paste Event"; paste_event.Tag = TAG_PASTE_EVENT; paste_event.DescriptionText = "Stuff happens"; paste_event.Enabled = false; paste_event.Click += paste_event_Click; // Create and add the copy button copy_event = (Office.CommandBarButton)Application.CommandBars["Cell"].Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, 1, true); copy_event.Style = Office.MsoButtonStyle.msoButtonCaption; copy_event.Caption = "Copy Event"; copy_event.Tag = TAG_COPY_EVENT; copy_event.DescriptionText = "Stuff happens"; copy_event.Enabled = false; copy_event.Click += copy_event_Click; } #region VSTO generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InternalStartup() { this.Startup += new System.EventHandler(ThisAddIn_Startup); this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); } #endregion } 

我正在使用Excel 2013,我知道有一个错误与右键单击上下文菜单有关(这就是为什么我使用的CommandBarControls而不是使用全局variablesforeach)。 任何工作stream程,你已经发现,工作将不胜感激!

清除:一切工作正常,唯一的问题是,如果closures添join,CommandBarButtons不从非活动工作簿的右键单击上下文菜单中删除。 如果在同一个会话期间重新打开“添加”,则会再次向所有工作簿提供“复制”和“粘贴”button,这意味着其上下文菜单没有正确更新的工作簿现在有2个“复制”button和2个“粘贴”button。

命令栏已被Office 2010弃用。您需要改为使用Fluent UI控件。

有关更多信息,请参阅在Office 2010中自定义上下文菜单 。