所以我已经完成了这个上下文菜单,除了菜单项的实际选择背后的事件似乎触发了多次。我第一次单击它时,它会触发一次,然后是两次,然后是 3 次。因此,在我刚刚给出的示例中,对于 3 次点击,它总共会触发 6 次 (1 + 2 + 3)。这是为什么?
下面是我如何创建菜单项的代码。我把它剥离成相关的部分;我省略了诸如 .Tag、.Visible 和 .Caption 属性之类的内容。我正在使用 .NET 3.5 和 VS 2008 构建它。
提前致谢!!
Private WithEvents ActiveExplorerCBars As Office.CommandBars
Private app As New Outlook.Application
Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
ActiveExplorerCBars = app.ActiveExplorer.CommandBars
AddHandler ActiveExplorerCBars.OnUpdate, AddressOf ActiveExplorerCBars_OnUpdate
End Sub
//This seems to get hit A LOT
Private Sub ActiveExplorerCBars_OnUpdate()
Dim bar As Office.CommandBar
If IgnoreCommandbarsChanges Then Exit Sub
bar = ActiveExplorerCBars.Item("Context Menu")
If Not bar Is Nothing Then
Dim addMenu As Boolean = False
//this For loop just makes sure the context is only available when the user right-clicks over a mail item
For Each mail As Outlook.MailItem In Application.ActiveExplorer().Selection
addMenu = True
Exit For
Next
If addMenu Then
AddContextDropdown(bar)
End If
End If
End Sub
Private Sub AddContextDropdown(ByVal ContextMenu As Office.CommandBar)
Dim RootPopup As Office.CommandBarPopup
Dim popupTaskItem As Office.CommandBarPopup
RootPopup = ContextMenu.FindControl(Type:=Office.MsoControlType.msoControlPopup, Tag:="Update task")
If RootPopup Is Nothing Then
ChangingBar(ContextMenu, Restore:=False)
RootPopup = ContextMenu.Controls.Add(Type:=Office.MsoControlType.msoControlPopup)
Dim thisTaskPopup As Office.CommandBarPopup
popupTaskItem = ContextMenu.FindControl(Type:=Office.MsoControlType.msoControlPopup, Tag:=task.EntryID)
If popupTaskItem Is Nothing Then
popupTaskItem = RootPopup.Controls.Add(Type:=Office.MsoControlType.msoControlPopup)
thisTaskPopup = popupTaskItem
AddActionButtons(thisTaskPopup)
End If
End If
End Sub
Private Sub AddActionButtons(ByVal puItem As Office.CommandBarPopup)
Dim puDeploy As Office.CommandBarPopup = puItem.Controls.Add(Type:=Office.MsoControlType.msoControlPopup)
Dim btnActionItem As Office.CommandBarControl = puDeploy.Controls.Add(Type:=Office.MsoControlType.msoControlButton)
Dim thisButton As Office.CommandBarButton = btnActionItem
AddHandler thisButton.Click, AddressOf OnContextClick
End Sub
//Click event
Public Sub OnContextClick(ByVal ctrl As Microsoft.Office.Core.CommandBarButton, ByRef CancelDefault As Boolean)
//This messagebox shows once the first time, twice the second, 3 times, etc
MessageBox.Show("Clicked: " & ctrl.Caption)
End Sub