Exchange上的公用文件夹上的ItemAdd事件

slo*_*ick 5 c# event-handling outlook-addin

我将事件处理程序附加到ItemAdd公用文件夹的事件时遇到问题.

问题是在几次成功调用后,事件处理程序停止被调用.

代码很简单.我有一个ThisAddIn类创建一个对象,该对象又ItemAdd在其构造函数中将事件附加到事件中.该功能只会弹出一个消息框.

请指出我正确的方向.我根本不明白在哪里寻找错误.

先谢谢你,阿纳托利

这是我尝试运行的测试代码:

public partial class ThisAddIn
{
    internal static Outlook.Folder posts_folder = null;
    private static test t;

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

        t = new test();
    }
{

class test
{
    public test()
    {
        System.Windows.Forms.MessageBox.Show("Attaching...");
        ThisAddIn.posts_folder.Items.ItemAdd +=new Microsoft.Office.Interop.Outlook.ItemsEvents_ItemAddEventHandler(Items_ItemAdd);
    }
    void Items_ItemAdd(object Item)
    {
        System.Windows.Forms.MessageBox.Show((Item as Outlook.PostItem).Subject);
    }
}
Run Code Online (Sandbox Code Playgroud)

slo*_*ick 3

持续的谷歌搜索完成了它的工作。我找到了如何解决该问题。看来我并不是唯一经历过这种事的人。

我添加了对我想要跟踪的文件夹的 Items 集合的引用到全局范围:

internal static class stor
{
    public static Outlook.Items i;
}

public partial class ThisAddIn
{
    internal static Outlook.Folder posts_folder = null;

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        // the code for finding a posts_folder is omitted

        stor.i = posts_folder.Items;
        stor.i.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Posts_Add);
    }

    static void Posts_Add(object Item)
    {
        System.Windows.Forms.MessageBox.Show("New item");
    }
{
Run Code Online (Sandbox Code Playgroud)

现在它按预期工作了。虽然我不明白他们说这是一个垃圾收集问题的所有细节。我的事件处理程序最终被扔进了垃圾箱。在全局范围内对 Items 集合的引用可以防止这种情况发生。