Context Menu on items

  • Thread starter Thread starter ivan.pololi
  • Start date Start date
I

ivan.pololi

Hello,

I developed an add-in to show a Context Menu on item right-click.

This was developed using Extensibility.IDTExtensibility2 interface in
Visual Studio, using the Microsoft Office 10.0 Library.

The add-in works fine on Office XP...any time I right-click an item,
it shows a context menu with an added button.

The weird thing happens on Office 2007... when I first right click the
context menu shows correctly. Then if I right-click immediately on
other items the menu doesn't always shows up with the added
button...instead if I wait at least three seconds between each right
click the context menu ALWAYS shows up correctly.

What could it be? I tried logging and debugging but I cannot solve the
issue.

Thank you,
Ivan

Here I post a snippet of my code:

Private Sub ActiveExplorerCBars_OnUpdate() Handles
_ActiveExplorerBars.OnUpdate

If _IgnoreCommandbarsChanges Then Exit Sub

If _ActiveExplorerBars.Item("Context Menu") IsNot Nothing Then
If _outApp.ActiveExplorer.Selection.Count > 0 Then
If _outApp.ActiveExplorer.Selection.Item(1).Class =
Outlook.OlObjectClass.olMail Then
AddContextButton(_ActiveExplorerBars.Item("Context
Menu"))
End If
End If
End If

End Sub
 
Here is the complete code:

Public Class Connect

Implements Extensibility.IDTExtensibility2

Private _applicationObject As Object
Private _addInInstance As Object
Private WithEvents _outApp As Outlook.Application
Private WithEvents _ActiveExplorerBars As
Microsoft.Office.Core.CommandBars
Private WithEvents _conButton As
Microsoft.Office.Core.CommandBarButton
Private _IgnoreCommandbarsChanges As Boolean
Private _currentUser As String = String.Empty

Public Sub OnBeginShutdown(ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnBeginShutdown
End Sub

Public Sub OnAddInsUpdate(ByRef custom As System.Array) Implements
Extensibility.IDTExtensibility2.OnAddInsUpdate
End Sub

Public Sub OnStartupComplete(ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnStartupComplete
_outApp = DirectCast(_applicationObject, Outlook.Application)
_ActiveExplorerBars = _outApp.ActiveExplorer.CommandBars
Dim rUser As New Redemption.SafeCurrentUser
_currentUser = rUser.Name
Log("Startup." & _outApp.Name & " " & _outApp.ProductCode)
End Sub

Public Sub OnDisconnection(ByVal RemoveMode As
Extensibility.ext_DisconnectMode, ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnDisconnection
End Sub

Public Sub OnConnection(ByVal application As Object, ByVal
connectMode As Extensibility.ext_ConnectMode, ByVal addInInst As
Object, ByRef custom As System.Array) Implements
Extensibility.IDTExtensibility2.OnConnection
Log("OnConnection")
_applicationObject = application
_addInInstance = addInInst
End Sub

'This fires when the user right-clicks a contact, and also for a
lot of other things!
Private Sub ActiveExplorerCBars_OnUpdate() Handles
_ActiveExplorerBars.OnUpdate

If _IgnoreCommandbarsChanges Then Exit Sub

If _ActiveExplorerBars.Item("Context Menu") IsNot Nothing Then
If _outApp.ActiveExplorer.Selection.Count > 0 Then
If _outApp.ActiveExplorer.Selection.Item(1).Class =
Outlook.OlObjectClass.olMail Then
AddContextButton(_ActiveExplorerBars.Item("Context
Menu"))
End If
End If
End If

End Sub

Private Sub AddContextButton(ByVal ContextMenu As
Microsoft.Office.Core.CommandBar)
Dim Control As Microsoft.Office.Core.CommandBarControl
Dim controlTag As String = "SalvaDocumentale"

'User cannot play with the Context Menu, so we know there is
at most only one copy of the control there
Control = ContextMenu.FindControl
(Type:=Microsoft.Office.Core.MsoControlType.msoControlButton,
Tag:=controlTag)

If Control Is Nothing Then

'Unprotect context menu
ChangingBar(ContextMenu, Restore:=False)

'Create the control
Control = ContextMenu.Controls.Add
(Type:=Microsoft.Office.Core.MsoControlType.msoControlButton)

''Set up control
Control.Tag = controlTag
Control.Caption = "Salva nel documentale..."
Control.Priority = 1
Control.Visible = True

'Reprotect context menu
ChangingBar(ContextMenu, Restore:=True)

'Hook the Click event
_conButton = DirectCast(Control,
Microsoft.Office.Core.CommandBarButton)
Else

Control.Priority = 1

End If

End Sub

'Called once to prepare for changes to the command bar, then again
with
'Restore = true once changes are complete.
Private Sub ChangingBar(ByVal bar As
Microsoft.Office.Core.CommandBar, ByVal Restore As Boolean)

Static oldProtectFromCustomize, oldIgnore As Boolean

If Restore Then

'Restore the Ignore Changes flag
_IgnoreCommandbarsChanges = oldIgnore


'Restore the protect-against-customization bit
If oldProtectFromCustomize Then bar.Protection = _
bar.Protection And
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize

Else

'Store the old Ignore Changes flag
oldIgnore = _IgnoreCommandbarsChanges


'Store old protect-against-customization bit setting then
clear
'CAUTION: Be careful not to alter the property if there is
no need,
'as changing the Protection will cause any visible
CommandBarPopup
'to disappear unless it is the popup we are altering.
oldProtectFromCustomize = bar.Protection And
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize
If oldProtectFromCustomize Then bar.Protection =
bar.Protection _
And Not
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize

End If
End Sub

Private Sub ContextButton_Click(ByVal Ctrl As
Microsoft.Office.Core.CommandBarButton, ByRef CancelDefault As
Boolean) Handles _conButton.Click

Try
Dim email As Outlook.MailItem
Dim rEmail As New Redemption.SafeMailItem
Dim nrEmail As Integer =
_outApp.ActiveExplorer.Selection.Count
Dim emailSalvate As Integer = 0
Dim errori As String = String.Empty
Dim fileDir As String = System.IO.Path.GetTempPath() &
"SalvaEmailDocumentale"
Dim progArg As String = String.Empty

'Verifica esistenza directory di appoggio
Dim folderExists As Boolean
folderExists = My.Computer.FileSystem.DirectoryExists
(fileDir)
If Not folderExists Then
My.Computer.FileSystem.CreateDirectory(fileDir)
End If

'Processa le email
For i As Integer = 1 To nrEmail
Dim filePath As String = String.Empty
Dim dateCreation As String = String.Empty
Try
email = CType(_outApp.ActiveExplorer.Selection.Item
(i), Outlook.MailItem)
dateCreation = email.CreationTime.Year &
email.CreationTime.Month & email.CreationTime.Day &
email.CreationTime.Hour & email.CreationTime.Minute &
email.CreationTime.Second
filePath = fileDir & "\" & NormalizzaEmailFileName
(email.Subject) & "." & dateCreation & ".msg"
rEmail.Item = email
rEmail.SaveAs(filePath,
Outlook.OlSaveAsType.olMSG)
progArg &= Chr(34) & filePath & Chr(34) & " "
emailSalvate += 1
Catch ex As Exception
errori &= "Email: [" & filePath & "] Dettagli: " &
ex.Message & vbCrLf
End Try
Next

'Status
Dim messaggio As String
If errori.Length > 0 Then
messaggio = "Si è verificato almeno un errore nel
salvataggio temporaneo delle email. Contattare l'ufficio informatico."
& vbCrLf & errori
Log(messaggio)
MessageBox.Show(messaggio, My.Application.Info.Title,
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If

If emailSalvate > 0 Then
'Esegue interfaccia documentale
Dim p As New Process
p.StartInfo.FileName = "\\pippo\pippo.exe"
p.StartInfo.Arguments = "E-mail"
p.StartInfo.Arguments &= " " & Chr(34) & fileDir & Chr
(34)
p.StartInfo.Arguments &= " " & progArg
p.Start()
'Al termine ripulisce cartella temporanea
p.WaitForExit()
My.Computer.FileSystem.DeleteDirectory(fileDir,
FileIO.DeleteDirectoryOption.DeleteAllContents)
End If


Catch ex As Exception
Log(ex.ToString)
End Try
End Sub

Private Function NormalizzaEmailFileName(ByVal name As String) As
String

name = Replace(name, "\", "")
name = Replace(name, "/", "")
name = Replace(name, ":", "")
name = Replace(name, "*", "")
name = Replace(name, "?", "")
name = Replace(name, """", "")
name = Replace(name, "<", "")
name = Replace(name, ">", "")
name = Replace(name, "|", "")

Return name
End Function

Private Sub Log(ByVal messaggio As String)
Dim fileLog As String = "\\pippo\pippo.log"
Try
messaggio = "[" & Now.ToString & "] [" & _currentUser & "]
" & messaggio & vbCrLf
My.Computer.FileSystem.WriteAllText(fileLog, messaggio,
True)
Catch ex As Exception
MessageBox.Show("Errore grave nel salvataggio log,
contattare l'ufficio informatico. Dettagli: " & ex.ToString,
My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub


End Class
 
Searching Google I found this guy who find out the cause of the
problem:

"If a user has the reading pane enabled in a folder and they right-
click on a mail item while the reading pane is still loading data,
then the custom item added to the context menu will not appear. "

This is real...deactivating the reading pane it works fine on Outlook
2007...

So... anyone has a solutions to this?

Thank you very much,
Ivan


Here is the complete code:

Public Class Connect

    Implements Extensibility.IDTExtensibility2

    Private _applicationObject As Object
    Private _addInInstance As Object
    Private WithEvents _outApp As Outlook.Application
    Private WithEvents _ActiveExplorerBars As
Microsoft.Office.Core.CommandBars
    Private WithEvents _conButton As
Microsoft.Office.Core.CommandBarButton
    Private _IgnoreCommandbarsChanges As Boolean
    Private _currentUser As String = String.Empty

    Public Sub OnBeginShutdown(ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnBeginShutdown
    End Sub

    Public Sub OnAddInsUpdate(ByRef custom As System.Array) Implements
Extensibility.IDTExtensibility2.OnAddInsUpdate
    End Sub

    Public Sub OnStartupComplete(ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnStartupComplete
        _outApp = DirectCast(_applicationObject, Outlook.Application)
        _ActiveExplorerBars = _outApp.ActiveExplorer.CommandBars
        Dim rUser As New Redemption.SafeCurrentUser
        _currentUser = rUser.Name
        Log("Startup." & _outApp.Name & " " & _outApp.ProductCode)
    End Sub

    Public Sub OnDisconnection(ByVal RemoveMode As
Extensibility.ext_DisconnectMode, ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnDisconnection
    End Sub

    Public Sub OnConnection(ByVal application As Object, ByVal
connectMode As Extensibility.ext_ConnectMode, ByVal addInInst As
Object, ByRef custom As System.Array) Implements
Extensibility.IDTExtensibility2.OnConnection
        Log("OnConnection")
        _applicationObject = application
        _addInInstance = addInInst
    End Sub

    'This fires when the user right-clicks a contact, and also for a
lot of other things!
    Private Sub ActiveExplorerCBars_OnUpdate() Handles
_ActiveExplorerBars.OnUpdate

        If _IgnoreCommandbarsChanges Then Exit Sub

        If _ActiveExplorerBars.Item("Context Menu") IsNot NothingThen
            If _outApp.ActiveExplorer.Selection.Count > 0 Then
                If _outApp.ActiveExplorer.Selection.Item(1).Class =
Outlook.OlObjectClass.olMail Then
                    AddContextButton(_ActiveExplorerBars.Item("Context
Menu"))
                End If
            End If
        End If

    End Sub

    Private Sub AddContextButton(ByVal ContextMenu As
Microsoft.Office.Core.CommandBar)
        Dim Control As Microsoft.Office.Core.CommandBarControl
        Dim controlTag As String = "SalvaDocumentale"

        'User cannot play with the Context Menu, so we know thereis
at most only one copy of the control there
        Control = ContextMenu.FindControl
(Type:=Microsoft.Office.Core.MsoControlType.msoControlButton,
Tag:=controlTag)

        If Control Is Nothing Then

            'Unprotect context menu
            ChangingBar(ContextMenu, Restore:=False)

            'Create the control
            Control = ContextMenu.Controls.Add
(Type:=Microsoft.Office.Core.MsoControlType.msoControlButton)

            ''Set up control
            Control.Tag = controlTag
            Control.Caption = "Salva nel documentale..."
            Control.Priority = 1
            Control.Visible = True

            'Reprotect context menu
            ChangingBar(ContextMenu, Restore:=True)

            'Hook the Click event
            _conButton = DirectCast(Control,
Microsoft.Office.Core.CommandBarButton)
        Else

            Control.Priority = 1

        End If

    End Sub

    'Called once to prepare for changes to the command bar, then again
with
    'Restore = true once changes are complete.
    Private Sub ChangingBar(ByVal bar As
Microsoft.Office.Core.CommandBar, ByVal Restore As Boolean)

        Static oldProtectFromCustomize, oldIgnore As Boolean

        If Restore Then

            'Restore the Ignore Changes flag
            _IgnoreCommandbarsChanges = oldIgnore

            'Restore the protect-against-customization bit
            If oldProtectFromCustomize Then bar.Protection = _
              bar.Protection And
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize

        Else

            'Store the old Ignore Changes flag
            oldIgnore = _IgnoreCommandbarsChanges

            'Store old protect-against-customization bit setting then
clear
            'CAUTION: Be careful not to alter the property ifthere is
no need,
            'as changing the Protection will cause any visible
CommandBarPopup
            'to disappear unless it is the popup we are altering.
            oldProtectFromCustomize = bar.Protection And
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize
            If oldProtectFromCustomize Then bar.Protection =
bar.Protection _
              And Not
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize

        End If
    End Sub

    Private Sub ContextButton_Click(ByVal Ctrl As
Microsoft.Office.Core.CommandBarButton, ByRef CancelDefault As
Boolean) Handles _conButton.Click

        Try
            Dim email As Outlook.MailItem
            Dim rEmail As New Redemption.SafeMailItem
            Dim nrEmail As Integer =
_outApp.ActiveExplorer.Selection.Count
            Dim emailSalvate As Integer = 0
            Dim errori As String = String.Empty
            Dim fileDir As String = System.IO.Path.GetTempPath() &
"SalvaEmailDocumentale"
            Dim progArg As String = String.Empty

            'Verifica esistenza directory di appoggio
            Dim folderExists As Boolean
            folderExists = My.Computer.FileSystem.DirectoryExists
(fileDir)
            If Not folderExists Then
                My.Computer.FileSystem.CreateDirectory(fileDir)
            End If

            'Processa le email
            For i As Integer = 1 To nrEmail
                Dim filePath As String = String.Empty
                Dim dateCreation As String = String.Empty
                Try
                    email = CType(_outApp.ActiveExplorer.Selection.Item
(i), Outlook.MailItem)
                    dateCreation = email.CreationTime.Year &
email.CreationTime.Month & email.CreationTime.Day &
email.CreationTime.Hour & email.CreationTime.Minute &
email.CreationTime.Second
                    filePath = fileDir & "\" & NormalizzaEmailFileName
(email.Subject) & "." & dateCreation & ".msg"
                    rEmail.Item = email
                    rEmail.SaveAs(filePath,
Outlook.OlSaveAsType.olMSG)
                    progArg &= Chr(34) & filePath &Chr(34) & " "
                    emailSalvate += 1
                Catch ex As Exception
                    errori &= "Email: [" & filePath& "] Dettagli: " &
ex.Message & vbCrLf
                End Try
            Next

            'Status
            Dim messaggio As String
            If errori.Length > 0 Then
                messaggio = "Si è verificato almeno un errore nel
salvataggio temporaneo delle email. Contattare l'ufficio informatico."
& vbCrLf & errori
                Log(messaggio)
                MessageBox.Show(messaggio, My.Application..Info.Title,
MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

            If emailSalvate > 0 Then
                'Esegue interfaccia documentale
                Dim p As New Process
                p.StartInfo.FileName = "\\pippo\pippo.exe"
                p.StartInfo.Arguments = "E-mail"
                p.StartInfo.Arguments &= " " & Chr(34) & fileDir & Chr
(34)
                p.StartInfo.Arguments &= " " & progArg
                p.Start()
                'Al termine ripulisce cartella temporanea
                p.WaitForExit()
                My.Computer.FileSystem.DeleteDirectory(fileDir,
FileIO.DeleteDirectoryOption.DeleteAllContents)
            End If

        Catch ex As Exception
            Log(ex.ToString)
        End Try
    End Sub

    Private Function NormalizzaEmailFileName(ByVal name As String) As
String

        name = Replace(name, "\", "")
        name = Replace(name, "/", "")
        name = Replace(name, ":", "")
        name = Replace(name, "*", "")
        name = Replace(name, "?", "")
        name = Replace(name, """", "")
        name = Replace(name, "<", "")
        name = Replace(name, ">", "")
        name = Replace(name, "|", "")

        Return name
    End Function

    Private Sub Log(ByVal messaggio As String)
        Dim fileLog As String = "\\pippo\pippo.log"
        Try
            messaggio = "[" & Now.ToString & "] [" & _currentUser & "]
" & messaggio & vbCrLf
            My.Computer.FileSystem.WriteAllText(fileLog, messaggio,
True)
        Catch ex As Exception
            MessageBox.Show("Errore grave nel salvataggio log,
contattare l'ufficio informatico. Dettagli: " & ex.ToString,
My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

End Class

I developed an add-in to show a Context Menu on item right-click.
This was developed using Extensibility.IDTExtensibility2 interface in
Visual Studio, using the Microsoft Office 10.0 Library.
The add-in works fine on Office XP...any time I right-click an item,
it shows a context menu with an added button.
The weird thing happens on Office 2007... when I first right click the
context menu shows correctly. Then if I right-click immediately on
other items the menu doesn't always shows up with the added
button...instead if I wait at least three seconds between each right
click the context menu ALWAYS shows up correctly.
What could it be? I tried logging and debugging but I cannot solve the
issue.
Thank you,
Ivan
Here I post a snippet of my code:
Private Sub ActiveExplorerCBars_OnUpdate() Handles
_ActiveExplorerBars.OnUpdate
        If _IgnoreCommandbarsChanges Then Exit Sub
        If _ActiveExplorerBars.Item("Context Menu") IsNot Nothing Then
            If _outApp.ActiveExplorer.Selection.Count > 0 Then
                If

...

leggi tutto- Nascondi testo citato

- Mostra testo citato -
 
Coding for context menus with any version of Outlook prior to Outlook 2007
is a hack. For Outlook 2007 you have all the new context menu events and
working with the context menus is supported by MS.

Outlook 2007 is slower than earlier versions and that's what's causing the
problem there.

What you might try is compiling a DLL that is compiled using the Outlook
2007 object model and loading it when you detect Outlook 2007. In that DLL
you pass in the trusted Outlook.Application object and instantiate the
Application.ContextXXX events you want to handle where ContextXXX represents
one or more of the available context events.

Something like that would allow you to handle the events correctly for
Outlook 2007 while still using the hacks needed for versions prior to
Outlook 2007.




Searching Google I found this guy who find out the cause of the
problem:

"If a user has the reading pane enabled in a folder and they right-
click on a mail item while the reading pane is still loading data,
then the custom item added to the context menu will not appear. "

This is real...deactivating the reading pane it works fine on Outlook
2007...

So... anyone has a solutions to this?

Thank you very much,
Ivan


Here is the complete code:

Public Class Connect

Implements Extensibility.IDTExtensibility2

Private _applicationObject As Object
Private _addInInstance As Object
Private WithEvents _outApp As Outlook.Application
Private WithEvents _ActiveExplorerBars As
Microsoft.Office.Core.CommandBars
Private WithEvents _conButton As
Microsoft.Office.Core.CommandBarButton
Private _IgnoreCommandbarsChanges As Boolean
Private _currentUser As String = String.Empty

Public Sub OnBeginShutdown(ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnBeginShutdown
End Sub

Public Sub OnAddInsUpdate(ByRef custom As System.Array) Implements
Extensibility.IDTExtensibility2.OnAddInsUpdate
End Sub

Public Sub OnStartupComplete(ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnStartupComplete
_outApp = DirectCast(_applicationObject, Outlook.Application)
_ActiveExplorerBars = _outApp.ActiveExplorer.CommandBars
Dim rUser As New Redemption.SafeCurrentUser
_currentUser = rUser.Name
Log("Startup." & _outApp.Name & " " & _outApp.ProductCode)
End Sub

Public Sub OnDisconnection(ByVal RemoveMode As
Extensibility.ext_DisconnectMode, ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnDisconnection
End Sub

Public Sub OnConnection(ByVal application As Object, ByVal
connectMode As Extensibility.ext_ConnectMode, ByVal addInInst As
Object, ByRef custom As System.Array) Implements
Extensibility.IDTExtensibility2.OnConnection
Log("OnConnection")
_applicationObject = application
_addInInstance = addInInst
End Sub

'This fires when the user right-clicks a contact, and also for a
lot of other things!
Private Sub ActiveExplorerCBars_OnUpdate() Handles
_ActiveExplorerBars.OnUpdate

If _IgnoreCommandbarsChanges Then Exit Sub

If _ActiveExplorerBars.Item("Context Menu") IsNot Nothing Then
If _outApp.ActiveExplorer.Selection.Count > 0 Then
If _outApp.ActiveExplorer.Selection.Item(1).Class =
Outlook.OlObjectClass.olMail Then
AddContextButton(_ActiveExplorerBars.Item("Context
Menu"))
End If
End If
End If

End Sub

Private Sub AddContextButton(ByVal ContextMenu As
Microsoft.Office.Core.CommandBar)
Dim Control As Microsoft.Office.Core.CommandBarControl
Dim controlTag As String = "SalvaDocumentale"

'User cannot play with the Context Menu, so we know there is
at most only one copy of the control there
Control = ContextMenu.FindControl
(Type:=Microsoft.Office.Core.MsoControlType.msoControlButton,
Tag:=controlTag)

If Control Is Nothing Then

'Unprotect context menu
ChangingBar(ContextMenu, Restore:=False)

'Create the control
Control = ContextMenu.Controls.Add
(Type:=Microsoft.Office.Core.MsoControlType.msoControlButton)

''Set up control
Control.Tag = controlTag
Control.Caption = "Salva nel documentale..."
Control.Priority = 1
Control.Visible = True

'Reprotect context menu
ChangingBar(ContextMenu, Restore:=True)

'Hook the Click event
_conButton = DirectCast(Control,
Microsoft.Office.Core.CommandBarButton)
Else

Control.Priority = 1

End If

End Sub

'Called once to prepare for changes to the command bar, then again
with
'Restore = true once changes are complete.
Private Sub ChangingBar(ByVal bar As
Microsoft.Office.Core.CommandBar, ByVal Restore As Boolean)

Static oldProtectFromCustomize, oldIgnore As Boolean

If Restore Then

'Restore the Ignore Changes flag
_IgnoreCommandbarsChanges = oldIgnore

'Restore the protect-against-customization bit
If oldProtectFromCustomize Then bar.Protection = _
bar.Protection And
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize

Else

'Store the old Ignore Changes flag
oldIgnore = _IgnoreCommandbarsChanges

'Store old protect-against-customization bit setting then
clear
'CAUTION: Be careful not to alter the property if there is
no need,
'as changing the Protection will cause any visible
CommandBarPopup
'to disappear unless it is the popup we are altering.
oldProtectFromCustomize = bar.Protection And
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize
If oldProtectFromCustomize Then bar.Protection =
bar.Protection _
And Not
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize

End If
End Sub

Private Sub ContextButton_Click(ByVal Ctrl As
Microsoft.Office.Core.CommandBarButton, ByRef CancelDefault As
Boolean) Handles _conButton.Click

Try
Dim email As Outlook.MailItem
Dim rEmail As New Redemption.SafeMailItem
Dim nrEmail As Integer =
_outApp.ActiveExplorer.Selection.Count
Dim emailSalvate As Integer = 0
Dim errori As String = String.Empty
Dim fileDir As String = System.IO.Path.GetTempPath() &
"SalvaEmailDocumentale"
Dim progArg As String = String.Empty

'Verifica esistenza directory di appoggio
Dim folderExists As Boolean
folderExists = My.Computer.FileSystem.DirectoryExists
(fileDir)
If Not folderExists Then
My.Computer.FileSystem.CreateDirectory(fileDir)
End If

'Processa le email
For i As Integer = 1 To nrEmail
Dim filePath As String = String.Empty
Dim dateCreation As String = String.Empty
Try
email = CType(_outApp.ActiveExplorer.Selection.Item
(i), Outlook.MailItem)
dateCreation = email.CreationTime.Year &
email.CreationTime.Month & email.CreationTime.Day &
email.CreationTime.Hour & email.CreationTime.Minute &
email.CreationTime.Second
filePath = fileDir & "\" & NormalizzaEmailFileName
(email.Subject) & "." & dateCreation & ".msg"
rEmail.Item = email
rEmail.SaveAs(filePath,
Outlook.OlSaveAsType.olMSG)
progArg &= Chr(34) & filePath & Chr(34) & " "
emailSalvate += 1
Catch ex As Exception
errori &= "Email: [" & filePath & "] Dettagli: " &
ex.Message & vbCrLf
End Try
Next

'Status
Dim messaggio As String
If errori.Length > 0 Then
messaggio = "Si è verificato almeno un errore nel
salvataggio temporaneo delle email. Contattare l'ufficio informatico."
& vbCrLf & errori
Log(messaggio)
MessageBox.Show(messaggio, My.Application.Info.Title,
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If

If emailSalvate > 0 Then
'Esegue interfaccia documentale
Dim p As New Process
p.StartInfo.FileName = "\\pippo\pippo.exe"
p.StartInfo.Arguments = "E-mail"
p.StartInfo.Arguments &= " " & Chr(34) & fileDir & Chr
(34)
p.StartInfo.Arguments &= " " & progArg
p.Start()
'Al termine ripulisce cartella temporanea
p.WaitForExit()
My.Computer.FileSystem.DeleteDirectory(fileDir,
FileIO.DeleteDirectoryOption.DeleteAllContents)
End If

Catch ex As Exception
Log(ex.ToString)
End Try
End Sub

Private Function NormalizzaEmailFileName(ByVal name As String) As
String

name = Replace(name, "\", "")
name = Replace(name, "/", "")
name = Replace(name, ":", "")
name = Replace(name, "*", "")
name = Replace(name, "?", "")
name = Replace(name, """", "")
name = Replace(name, "<", "")
name = Replace(name, ">", "")
name = Replace(name, "|", "")

Return name
End Function

Private Sub Log(ByVal messaggio As String)
Dim fileLog As String = "\\pippo\pippo.log"
Try
messaggio = "[" & Now.ToString & "] [" & _currentUser & "]
" & messaggio & vbCrLf
My.Computer.FileSystem.WriteAllText(fileLog, messaggio,
True)
Catch ex As Exception
MessageBox.Show("Errore grave nel salvataggio log,
contattare l'ufficio informatico. Dettagli: " & ex.ToString,
My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

End Class

I developed an add-in to show a Context Menu on item right-click.
This was developed using Extensibility.IDTExtensibility2 interface in
Visual Studio, using the Microsoft Office 10.0 Library.
The add-in works fine on Office XP...any time I right-click an item,
it shows a context menu with an added button.
The weird thing happens on Office 2007... when I first right click the
context menu shows correctly. Then if I right-click immediately on
other items the menu doesn't always shows up with the added
button...instead if I wait at least three seconds between each right
click the context menu ALWAYS shows up correctly.
What could it be? I tried logging and debugging but I cannot solve the
issue.
Thank you,
Ivan
Here I post a snippet of my code:
Private Sub ActiveExplorerCBars_OnUpdate() Handles
_ActiveExplorerBars.OnUpdate
If _IgnoreCommandbarsChanges Then Exit Sub
If _ActiveExplorerBars.Item("Context Menu") IsNot Nothing Then
If _outApp.ActiveExplorer.Selection.Count > 0 Then
If

...

leggi tutto- Nascondi testo citato

- Mostra testo citato -
 
Ok, very smart.

What is the best way to detect the Outlook version?

Thanx,
Ivan

Coding for context menus with any version of Outlook prior to Outlook 2007
is a hack. For Outlook 2007 you have all the new context menu events and
working with the context menus is supported by MS.

Outlook 2007 is slower than earlier versions and that's what's causing the
problem there.

What you might try is compiling a DLL that is compiled using the Outlook
2007 object model and loading it when you detect Outlook 2007. In that DLL
you pass in the trusted Outlook.Application object and instantiate the
Application.ContextXXX events you want to handle where ContextXXX represents
one or more of the available context events.

Something like that would allow you to handle the events correctly for
Outlook 2007 while still using the hacks needed for versions prior to
Outlook 2007.




Searching Google I found this guy who find out the cause of the
problem:

"If a user has the reading pane enabled in a folder and they right-
click on a mail item while the reading pane is still loading data,
then the custom item added to the context menu will not appear. "

This is real...deactivating the reading pane it works fine on Outlook
2007...

So... anyone has a solutions to this?

Thank you very much,
Ivan

Here is the complete code:
Public Class Connect
Implements Extensibility.IDTExtensibility2
Private _applicationObject As Object
Private _addInInstance As Object
Private WithEvents _outApp As Outlook.Application
Private WithEvents _ActiveExplorerBars As
Microsoft.Office.Core.CommandBars
Private WithEvents _conButton As
Microsoft.Office.Core.CommandBarButton
Private _IgnoreCommandbarsChanges As Boolean
Private _currentUser As String = String.Empty
Public Sub OnBeginShutdown(ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnBeginShutdown
End Sub
Public Sub OnAddInsUpdate(ByRef custom As System.Array) Implements
Extensibility.IDTExtensibility2.OnAddInsUpdate
End Sub
Public Sub OnStartupComplete(ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnStartupComplete
_outApp = DirectCast(_applicationObject, Outlook.Application)
_ActiveExplorerBars = _outApp.ActiveExplorer.CommandBars
Dim rUser As New Redemption.SafeCurrentUser
_currentUser = rUser.Name
Log("Startup." & _outApp.Name & " " & _outApp.ProductCode)
End Sub
Public Sub OnDisconnection(ByVal RemoveMode As
Extensibility.ext_DisconnectMode, ByRef custom As System.Array)
Implements Extensibility.IDTExtensibility2.OnDisconnection
End Sub
Public Sub OnConnection(ByVal application As Object, ByVal
connectMode As Extensibility.ext_ConnectMode, ByVal addInInst As
Object, ByRef custom As System.Array) Implements
Extensibility.IDTExtensibility2.OnConnection
Log("OnConnection")
_applicationObject = application
_addInInstance = addInInst
End Sub
'This fires when the user right-clicks a contact, and also for a
lot of other things!
Private Sub ActiveExplorerCBars_OnUpdate() Handles
_ActiveExplorerBars.OnUpdate
If _IgnoreCommandbarsChanges Then Exit Sub
If _ActiveExplorerBars.Item("Context Menu") IsNot Nothing Then
If _outApp.ActiveExplorer.Selection.Count > 0 Then
If _outApp.ActiveExplorer.Selection.Item(1).Class =
Outlook.OlObjectClass.olMail Then
AddContextButton(_ActiveExplorerBars.Item("Context
Menu"))
End If
End If
End If
Private Sub AddContextButton(ByVal ContextMenu As
Microsoft.Office.Core.CommandBar)
Dim Control As Microsoft.Office.Core.CommandBarControl
Dim controlTag As String = "SalvaDocumentale"
'User cannot play with the Context Menu, so we know there is
at most only one copy of the control there
Control = ContextMenu.FindControl
(Type:=Microsoft.Office.Core.MsoControlType.msoControlButton,
Tag:=controlTag)
If Control Is Nothing Then
'Unprotect context menu
ChangingBar(ContextMenu, Restore:=False)
'Create the control
Control = ContextMenu.Controls.Add
(Type:=Microsoft.Office.Core.MsoControlType.msoControlButton)
''Set up control
Control.Tag = controlTag
Control.Caption = "Salva nel documentale..."
Control.Priority = 1
Control.Visible = True
'Reprotect context menu
ChangingBar(ContextMenu, Restore:=True)
'Hook the Click event
_conButton = DirectCast(Control,
Microsoft.Office.Core.CommandBarButton)
Else
Control.Priority = 1
'Called once to prepare for changes to the command bar, then again
with
'Restore = true once changes are complete.
Private Sub ChangingBar(ByVal bar As
Microsoft.Office.Core.CommandBar, ByVal Restore As Boolean)
Static oldProtectFromCustomize, oldIgnore As Boolean
If Restore Then
'Restore the Ignore Changes flag
_IgnoreCommandbarsChanges = oldIgnore
'Restore the protect-against-customization bit
If oldProtectFromCustomize Then bar.Protection = _
bar.Protection And
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize

'Store the old Ignore Changes flag
oldIgnore = _IgnoreCommandbarsChanges
'Store old protect-against-customization bit setting then
clear
'CAUTION: Be careful not to alter the property if there is
no need,
'as changing the Protection will cause any visible
CommandBarPopup
'to disappear unless it is the popup we are altering.
oldProtectFromCustomize = bar.Protection And
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize
If oldProtectFromCustomize Then bar.Protection =
bar.Protection _
And Not
Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize
End If
End Sub
Private Sub ContextButton_Click(ByVal Ctrl As
Microsoft.Office.Core.CommandBarButton, ByRef CancelDefault As
Boolean) Handles _conButton.Click
Try
Dim email As Outlook.MailItem
Dim rEmail As New Redemption.SafeMailItem
Dim nrEmail As Integer =
_outApp.ActiveExplorer.Selection.Count
Dim emailSalvate As Integer = 0
Dim errori As String = String.Empty
Dim fileDir As String = System.IO.Path.GetTempPath() &
"SalvaEmailDocumentale"
Dim progArg As String = String.Empty
'Verifica esistenza directory di appoggio
Dim folderExists As Boolean
folderExists = My.Computer.FileSystem.DirectoryExists
(fileDir)
If Not folderExists Then
My.Computer.FileSystem.CreateDirectory(fileDir)
End If
'Processa le email
For i As Integer = 1 To nrEmail
Dim filePath As String = String.Empty
Dim dateCreation As String = String.Empty
Try
email = CType(_outApp.ActiveExplorer.Selection.Item
(i), Outlook.MailItem)
dateCreation = email.CreationTime.Year &
email.CreationTime.Month & email.CreationTime.Day &
email.CreationTime.Hour & email.CreationTime.Minute &
email.CreationTime.Second
filePath = fileDir & "\" & NormalizzaEmailFileName
(email.Subject) & "." & dateCreation & ".msg"
rEmail.Item = email
rEmail.SaveAs(filePath,
Outlook.OlSaveAsType.olMSG)
progArg &= Chr(34) & filePath & Chr(34) & " "
emailSalvate += 1
Catch ex As Exception
errori &= "Email: [" & filePath & "] Dettagli: " &
ex.Message & vbCrLf
End Try
Next
'Status
Dim messaggio As String
If errori.Length > 0 Then
messaggio = "Si è verificato almeno un errore nel
salvataggio temporaneo delle email. Contattare l'ufficio informatico."
& vbCrLf & errori
Log(messaggio)
MessageBox.Show(messaggio, My.Application.Info.Title,
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
If emailSalvate > 0 Then
'Esegue interfaccia documentale
Dim p As New Process
p.StartInfo.FileName = "\\pippo\pippo.exe"
p.StartInfo.Arguments = "E-mail"
p.StartInfo.Arguments &= " " & Chr(34) & fileDir & Chr
(34)
p.StartInfo.Arguments &= " " & progArg
p.Start()
'Al termine ripulisce cartella temporanea
p.WaitForExit()
My.Computer.FileSystem.DeleteDirectory(fileDir,
FileIO.DeleteDirectoryOption.DeleteAllContents)
End If
Catch ex As Exception
Log(ex.ToString)
End Try
End Sub
Private Function NormalizzaEmailFileName(ByVal name As String) As
String
name = Replace(name, "\", "")
name = Replace(name, "/", "")
name = Replace(name, ":", "")
name = Replace(name, "*", "")
name = Replace(name, "?", "")
name = Replace(name, """", "")
name = Replace(name, "<", "")
name = Replace(name, ">", "")
name = Replace(name, "|", "")
Return name
End Function
Private Sub Log(ByVal messaggio As String)
Dim fileLog As String = "\\pippo\pippo.log"
Try
messaggio = "[" & Now.ToString & "] [" & _currentUser & "]
" & messaggio & vbCrLf
My.Computer.FileSystem.WriteAllText(fileLog, messaggio,
True)
Catch ex As Exception
MessageBox.Show("Errore grave nel salvataggio log,
contattare l'ufficio informatico. Dettagli: " & ex.ToString,
My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
End Class
On 27 Gen, 14:36, (e-mail address removed) wrote:

...

leggi tutto- Nascondi testo citato

- Mostra testo citato -
 
Outlook.Application.Version. It's a string so you'd have to parse the
string. I usually look at the 2 leftmost characters, if they are "12" it's
Outlook 2007, "11" is Outlook 2003, etc.




Ok, very smart.

What is the best way to detect the Outlook version?

Thanx,
Ivan
 
Ok, so at first I have to load the Outlook 10 library in order to
detect the version and then if it is the 2007 version I load its
library, correct?

Thanx,
Ivan
 
You can't load the libraries it's what's referenced when you compile.

You would create a project to create a DLL and use the Outlook.12 library
for that (Outlook 2007). The main code only references the earliest version
of Outlook you need to support. If that code discovers that
Outlook.Application.Version.StartsWith("12") == true then it loads the DLL
that handles the Outlook 2007 context menus and doesn't instantiate the
CommandBars.OnUpdate() event handler since context menus will be handled
using that DLL.
 
I am trying to add a custom menu item in the outlook context menu, the code I
have is as follows (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using System.Windows.Forms;
using Microsoft.Office.Tools.Outlook;
using Microsoft.Office.Core;
using Microsoft.VisualStudio.Tools.Applications.Runtime;

namespace ContextMenu
{
public partial class ThisAddIn
{

//---

private Microsoft.Office.Core.CommandBars mCommandBars;




private void ThisApplication_OnCBarsUpdate()
{
foreach (Microsoft.Office.Core.CommandBar bar in
Application.ActiveExplorer().CommandBars)
{
if (bar.Name == "Context Menu")
{
MsoBarProtection oldProtection = bar.Protection;
bar.Protection = 0;

foreach (Office.CommandBarControl ctrl in
bar.Controls)
{
if (ctrl.Caption == "Ask to this person")
{
return;
}
}


CommandBarButton checkInMenuItem =
(CommandBarButton)bar.FindControl(MsoControlType.msoControlButton,
Type.Missing, "Ask to this person", Type.Missing, Type.Missing);



if (checkInMenuItem == null)
{
checkInMenuItem =
(CommandBarButton)bar.Controls.Add(MsoControlType.msoControlButton,
Type.Missing, Type.Missing, Type.Missing, true);
checkInMenuItem.Caption = "Ask to this person";

checkInMenuItem.Click += new
_CommandBarButtonEvents_ClickEventHandler(checkInMenuItem_Click);
}


//bar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton,
//missing, missing, missing, false);


//button.Caption = "Track Discussion";
//button.Visible = true;
bar.Protection = oldProtection;
}
}
}

void checkInMenuItem_Click(CommandBarButton Ctrl, ref bool
CancelDefault)
{
MessageBox.Show("test");
}


//protected void checkInMenuItem_Click(object sender, System)
//{
// MessageBox.Show("Ask to this person");
//}

//---
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
mCommandBars = Application.ActiveExplorer().CommandBars;
mCommandBars.OnUpdate += new

Microsoft.Office.Core._CommandBarsEvents_OnUpdateEventHandler(ThisApplication_OnCBarsUpdate);

}

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

}




#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




}

}

But the item is not being displayed in the context menu. Please help me in
this regard.
 
I am trying to add a menu item in the outlook context menu, the code I have
in C# is as follows..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using System.Windows.Forms;
using Microsoft.Office.Tools.Outlook;
using Microsoft.Office.Core;
using Microsoft.VisualStudio.Tools.Applications.Runtime;

namespace ContextMenu
{
public partial class ThisAddIn
{

//---

private Microsoft.Office.Core.CommandBars mCommandBars;




private void ThisApplication_OnCBarsUpdate()
{
foreach (Microsoft.Office.Core.CommandBar bar in
Application.ActiveExplorer().CommandBars)
{
if (bar.Name == "Context Menu")
{
MsoBarProtection oldProtection = bar.Protection;
bar.Protection = 0;

foreach (Office.CommandBarControl ctrl in
bar.Controls)
{
if (ctrl.Caption == "Ask to this person")
{
return;
}
}


CommandBarButton checkInMenuItem =
(CommandBarButton)bar.FindControl(MsoControlType.msoControlButton,
Type.Missing, "Ask to this person", Type.Missing, Type.Missing);



if (checkInMenuItem == null)
{
checkInMenuItem =
(CommandBarButton)bar.Controls.Add(MsoControlType.msoControlButton,
Type.Missing, Type.Missing, Type.Missing, true);
checkInMenuItem.Caption = "Ask to this person";

checkInMenuItem.Click += new
_CommandBarButtonEvents_ClickEventHandler(checkInMenuItem_Click);
}


//bar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton,
//missing, missing, missing, false);


//button.Caption = "Track Discussion";
//button.Visible = true;
bar.Protection = oldProtection;
}
}
}

void checkInMenuItem_Click(CommandBarButton Ctrl, ref bool
CancelDefault)
{
MessageBox.Show("test");
}


//protected void checkInMenuItem_Click(object sender, System)
//{
// MessageBox.Show("Ask to this person");
//}

//---
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
mCommandBars = Application.ActiveExplorer().CommandBars;
mCommandBars.OnUpdate += new

Microsoft.Office.Core._CommandBarsEvents_OnUpdateEventHandler(ThisApplication_OnCBarsUpdate);

}

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

}




#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




}

}


But the menu item is not being displayed. Please help me get this problem
solved..
 
Did you look at the context menu handler examples at www.outlookcode.com to
see how to handle this? If the examples there aren't in C# they certainly
are in VBA/VB6 and you can translate them into C#.
 
Hi Kan Slovak, Yeah there are examples developed using C#, but not the one I
want for adding context menu item, but Kan I am sure this is the correct
code, but I am unable to see the item. Anyways, can you give me the exact
code in VBA or any other language, Ill convert it to C# and check...
 
private void ThisApplication_OnCBarsUpdate()

When I debug the code I am I came to know the CommandBar Context Menu is in
the seen in the loop, So the inner if condition is never executed. Please
help me understand what is the problem, why dont the Context Menu CommandBar
is not available in the code. Please help it is taking me real long time.
 
Sorry, mistakes in the last post..


When I debug the code, I came to know the CommandBar Context Menu is not
seen in the loop, So the inner if condition is never executed. Please
help me understand what is the problem, why dont the Context Menu CommandBar
is not available in the code. Please help it is taking me real long time.
 
Search at outlookcode.com for "context menu" and start looking at the
results. There are a number of VBA examples.
 
The context menu item is only there in the CommandBars collection if you
have right-clicked and are bringing up a context menu. Otherwise the code
should exit without finding the "Context Menu" CommandBar object. It's
certainly there when I run code that looks for it.
 
Back
Top