views:

889

answers:

1

I've created a VSTO in C# that is supposed to hook Outlook 2007's NewMailEx event. However, it doesn't fire sometimes when I do a manual send/receive, or when there is only 1 unread mail in the inbox. It almost seems as if it fires on the inbox BEFORE the message actually arrives.

Is there a better way of monitoring for new messages every single time besides ItemAdd or NewMailEX using VSTO?

+2  A: 

The reason is: "GC collect the .NET object, whichc wrapps COM object from Outlook )". The solution is hold reference to this .NET object. The most ease way is:

// this is helper collection.
// there are all wrapper objects
// , which should not be collected by GC
private List<object> holdedObjects = new List<object>();

// hooks necesary events
void HookEvents() {
    // finds button in commandbars
    CommandBarButton btnSomeButton = FindCommandBarButton( "MyButton ");
    // hooks "Click" event
    btnSomeButton.Click += btnSomeButton_Click;
    // add "btnSomeButton" object to collection and
    // and prevent themfrom collecting by GC
    holdedObjects.Add( btnSomeButton );
}

You can also have a special field for this ( and others ) concrete button ( or another objects ), if you want. But this is most common solution.

TcKs