2
votes

I plan to retrieve the mail item of the selected email on every chance of selected outlook email, but the event handle only gets triggered on startup, and sometimes properly. I can't seem to find what's causing the issue, most forums leads to a dead end, hence this post.

Anyway, here's a snippet of my Startup method:

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

        this.Application.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);

        Outlook.Explorer currentExplorer = this.Application.ActiveExplorer();
        currentExplorer.SelectionChange += new Outlook.ExplorerEvents_10_SelectionChangeEventHandler(CurrentExplorer_Event);

        outlookNameSpace = this.Application.GetNamespace("MAPI");
        inbox = outlookNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
        items = inbox.Items;
        items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd);

    }

and here's a snippet of my CurrentExplorer_Event method:

private void CurrentExplorer_Event()
    {
        newSelectedEmail = new Email();
        Outlook.MAPIFolder selectedFolder = this.Application.ActiveExplorer().CurrentFolder;
        try
        {
            if (this.Application.ActiveExplorer().Selection.Count > 0)
            {
                Object selObject = this.Application.ActiveExplorer().Selection[1];
                if (selObject is Outlook.MailItem)
                {
                    Outlook.MailItem mailItem = (selObject as Outlook.MailItem);
                    GetEmailInfoFromOutlookEmail(mailItem);
                }

            }
        }
        catch (Exception ex)
        {
            Operations.SaveLogToFile(LogType.Error, "Main - CurrentExplorer_Event", ex.Message, ex.StackTrace);
        }
    }

Any help is greatly appreciated. Thank you!

1

1 Answers

2
votes

The variable raising the events (currentExplorer) is a local variable. As soon as it goes out of scope, it becomes eligible to be released by the Garbage Collector. As soon as that happens, no events are raised.

Move the declaration of that variable to the class level.