Outlook 2016 VSTO Folder Add item event fires only once

随声附和 提交于 2021-02-11 13:27:59

问题


I have an add-in, I want to do something when the email sent successful, I write:

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        Outlook.Application application = this.Application;

        var sentMail = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
        sentMail.Items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Items_ItemAdd);
    }

    void Items_ItemAdd(object item)
    {
      // do something
    }

But my method runs only one when I sent first email success, the next emails not fires event.

Please help me!


回答1:


You are setting an event handler on a implicit local variable. As soon as that variable is released by the Garbage Collector, no events will fire. You need to have a global (class) Items variable:

private Outlook.Items _items;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        Outlook.Application application = this.Application;

        _items = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail).Items;
        _items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Items_ItemAdd);
    }



回答2:


I wanted to post my solution to this problem as well. I tried pretty much everything that was suggested on stackoverflow and nothing worked well, including adding 'Items' to a list so it doesn't get garbage collected, etc.

What worked perfectly for me was to tell the GC to not collect 'Items' explicitly and then it started picking up every new item in the Inbox.

Here's the code I ended up using:

public partial class ThisAddIn
{
    // Keep a static copy of the Inbox and Items
    private static MAPIFolder Inbox { get; set; }
    private static Items Items { get; set; }

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        Inbox = Application.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
        Items = Inbox.Items;
        Items.ItemAdd += new ItemsEvents_ItemAddEventHandler(ProcessesEmail);

        // Tell the GC to *not* collect these objects
        GC.KeepAlive(Inbox);
        GC.KeepAlive(Items);
    }

    public static void ProcessesEmail(object Item)
    {
        // Rest of your code here
    }
}


来源:https://stackoverflow.com/questions/50506817/outlook-2016-vsto-folder-add-item-event-fires-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!