Search code examples
wpfvb.netoutlookcom-automation

Adding a Handler to .ItemAdd Outlook Event


My code:

Imports Microsoft.Office.Interop
Imports OpenQA.Selenium
Imports OpenQA.Selenium.Chrome
Imports System.Text
Imports System.Windows.Threading
Imports UiPath
Imports UiPath.Orchestrator.Extensibility
Imports System.IO
Imports System.Net.NetworkInformation
Imports EASendMail
Imports VB = Microsoft.VisualBasic

Class MainWindow


Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)


    'Dim OutlookApp As New Outlook.Application
    Dim OutlookApp As Outlook.Application = GetObject(, "Outlook.Application")
    Dim Inbox = OutlookApp.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Items

    AddHandler Inbox.ItemAdd, AddressOf Inbox_ItemAdd
    'Inbox.ItemAdd += New Outlook.ItemsEvents_ItemAddEventHandler(AddressOf Inbox_ItemAdd)
    'This line does not work, but it works in the C# stack question for some reason

End Sub

Public Sub Inbox_ItemAdd(ByVal Item As Object)
    Dim mail As Outlook.MailItem = CType(Item, Outlook.MailItem)

    If Item IsNot Nothing Then
        MsgBox("Received")
    End If
End Sub

End Class

I tried both adding a handler from the .ItemAdd to my method called Inbox_ItemAdd and tried a solution from a different stackoverflow question like this: Inbox.ItemAdd += New Outlook.ItemsEvents_ItemAddEventHandler(AddressOf Inbox_ItemAdd).

I'm out of ideas.

The issue is that the Inbox_ItemAdd will not trigger even if I use the AddHandler.


Solution

  • You should keep the object that raises the event alive by storing it in a field:

    Class MainWindow
    
        Dim Inbox As Outlook.Items
    
        Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
    
            ...
            Inbox = OutlookApp.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Items
    
            AddHandler Inbox.ItemAdd, AddressOf Inbox_ItemAdd
    
        End Sub
    
        Public Sub Inbox_ItemAdd(ByVal Item As Object)
            ...
        End Sub
    
    End Class