在VB.Net中响应多个VSTO上下文菜单

时间:2017-10-04 04:44:57

标签: vb.net vsto

尝试使用VB.Net构建VSTO。 我确实问过,它必须是VB.Net。

应用程序级别ADDIN针对EXCEL

我的挑战是尝试构建一个具有不确定数量的子项的上下文菜单。

我可以制作菜单,但我目前只能点击onClick来触发最后一个按钮。

我已经对此进行了彻底的研究,但我找不到VB的例子。 VB中有很多添加简单上下文菜单的例子。

C#中有一些例子,但你可以这样做

 cb.Click += cbButton_Clicked;

我还没有弄清楚如何在VB中这样做,因此问题。 整个代码如下。我可以点击前5个按钮中的任何一个,但没有任何反应。当我点击最后一个时,它会按预期触发一个消息框。

我将有一个不确定数量的菜单项,所以我不能只添加X#处理程序。

Public Class ThisAddIn
 Dim WithEvents cb As CommandBarButton
    Dim TradeName As String = "MyMenu"
    Private Sub ThisAddIn_Startup() Handles Me.Startup

        ' AddHandler Application.WorkbookBeforeSave, AddressOf Application_WorkbookBeforeSave

        AddHandler Application.NewWorkbook, AddressOf ThisWorkbook_NewWorkbook

    End Sub


    Private Sub ThisWorkbook_NewWorkbook(wb As Microsoft.Office.Interop.Excel.Workbook)

        AddMenu2()
    End Sub



    Public Function GetCellContextMenu() As Office.CommandBar

        Return Application.CommandBars("Cell")
    End Function


    Public Sub AddMenu2()
        Dim Bar As Microsoft.Office.Core.CommandBar
        Dim NewControl As Microsoft.Office.Core.CommandBarControl

        Try

            Application.CommandBars("Cell").Controls(TradeName).Delete()
        Catch ex As Exception

        End Try


        Bar = Application.CommandBars("Cell")
        NewControl = Bar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlPopup, Id:=1, Temporary:=True)

        With NewControl
            .Caption = TradeName
            .BeginGroup = True
            .TooltipText = TradeName & " Queries."
        End With

        Dim ag As New fvConnectionSuperAg
        Dim l As List(Of fvConnection) = ag.Items

        For Each conn As fvConnection In l

            cb = NewControl.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton)
            With cb
                .Caption = conn.Name.Value
                .FaceId = 218
                   ' HERE IS WHERE  I THINK I SHOULD CONNECT THE HANDLER 
            End With

下一步

    End Sub

    Private Sub cb_Click(Ctrl As CommandBarButton, ByRef CancelDefault As Boolean) Handles cb.Click
        MsgBox(Ctrl.Caption, MsgBoxStyle.ApplicationModal, "Fast View")
    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

永远不会失败,在SO上发帖会让你在脑海中澄清问题,这通常会导致答案....

我在本文中找到了以编程方式添加事件处理程序的答案。真的与VSTO无关。

http://www.thescarms.com/dotnet/EventHandler.aspx

这是以前发布的摘录 创建按钮后立即调用 ADDHANDLER

 cb = NewControl.Controls.Add (Microsoft.Office.Core.MsoControlType.msoControlButton)
            AddHandler cb.Click, AddressOf cb_Click
            With cb
                .Caption = conn.Name.Value
                .FaceId 
            End With