C# - How to find which mailItem user is closing in outlook [com-addin]

133 Views Asked by At

I am currently trying to do some operations on mailItem close. With the Microsoft ItemEvents_10_Event.Close event doesn't provide which mailItem is getting closed.

If the user opened multiple emails and closes one of them, how can I get to know which email item is selected to close? is there any property to tell that this mail item is closing?

//New inspector event:
m_inspectors.NewInspector += m_inspectors_NewInspector;

//Trigerring mailItem close event from the new inspector.
 void m_inspectors_NewInspector(Interop.Inspector Inspector)
        {
            Interop.MailItem me = null;            
            try
            {
                me = Inspector.CurrentItem as Interop.MailItem;                
                if (me != null)
                {
                    ((Interop.ItemEvents_10_Event)me).Close += OutlookApp_Close;
                    //some operations.
                }
            }
            catch
            {
               
            }
            finally
            {
                if (me != null)
                {
                    me.ReleaseComObject();
                    me = null;
                }
            }
        }
//mailItem close event
 private void OutlookApp_Close(ref bool Cancel)
        {
           //here I need to get the exact mailItem that is about to close.
        }`

Basically, is there possible to get the exact mailItem on any of the close events?

1

There are 1 best solutions below

1
On BEST ANSWER

Create a wrapper class that takes MailItem as a parameter to its constructor and keeps it in a member variable. Make the event handler a method on that class. When it fires, you will have the member variable that references the MailItem object.

    MailItemWrapper wrapper = new MailItemWrapper(me);
    ...
    public class MailItemWrapper
    {
      private MailItem _mailItem;
      public MailItemWrapper(MailItem mailItem)
      {
        _mailItem = mailItem;
        ((Interop.ItemEvents_10_Event)_mailItem).Close += On_Close; 
      }
      private void On_Close(ref bool Cancel)
      {
        MessageBox.Show(_mailItem.Subject);
        Marshal.ReleaseComObject(_mailItem);
        _mailItem = null;
        //todo: if the wrapper is stored in a list, remove self from that list
      }
    }