C# VSTO给Excel添加右键菜单并添加点击的click事件

Excel.Application app;
private static CommandBarButton btn;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    app = Globals.ThisAddIn.Application;
    app.SheetSelectionChange += App_SheetSelectionChange;
}

private void App_SheetSelectionChange(object Sh, Excel.Range Target)
{            
     
          //右键重置避免按钮重复
  CommandBar currentMenuBar = app.CommandBars["cell"];
                currentMenuBar.Reset();
//删除右键
                foreach (CommandBarControl temp_contrl in currentMenuBar.Controls)
                {
                    string t = temp_contrl.Tag;
                    if (customMenuTags.Contains(t))
                    {
                        if (temp_contrl.Type == MsoControlType.msoControlPopup)
                        {
                            temp_contrl.Delete();
                            GC.Collect();
                            GC.WaitForPendingFinalizers();
                        }
                        else
                        {
                            try
                            {
                                temp_contrl.Delete();
                            }
                            catch { }
                        }
                    }
                }

  //解决事件连续触发
                        btn = null;
                        GC.Collect();
                        GC.WaitForPendingFinalizers();


//定义右键菜单
                btn=
                            (CommandBarButton)currentMenuBar.Controls.Add(
                                MsoControlType.msoControlButton, missing, missing, missing);


                        btn.Tag = "test";
                        btn.Caption = "测试";
                        btn.Click += NewControl_Click;

//显示
foreach (CommandBarControl temp_contrl in currentMenuBar.Controls)
                {
                    string t = temp_contrl.Tag;
                    if (customMenuTags.Contains(t))
                    {
                        if (temp_contrl.Type == MsoControlType.msoControlButtonPopup)
                        {
                            ((CommandBarPopup)temp_contrl).Visible = true;
                        }
                        else
                        {
                            try
                            {
                                ((CommandBarButton)temp_contrl).Visible = true;
                            }
                            catch { }
                        }
                    }
                }
                
}

private void NewControl_Click(Office.CommandBarButton Ctrl, ref bool CancelDefault)
{
    System.Windows.Forms.MessageBox.Show("Test");
}
 this.Shutdown += new EventHandler(ThisAddIn_Shutdown);
 
private void ThisAddIn_Shutdown(object sender, EventArgs e)
        {
           //卸载重置右键菜单
            CommandBar currentMenuBar = app.CommandBars["cell"];
            currentMenuBar.Reset();
        }

 

你可能感兴趣的:(c#,vsto)