This project has moved and is read-only. For the latest updates, please go here.

Handle Outlook new contact event

Jan 29, 2014 at 5:34 PM
Hi, I'm developing an outlook addin which needs to respond to a new contact event, but it's not working.
I've tried:
void Addin_OnStartupComplete(ref Array custom)
{
    Outlook._NameSpace outlookNs = _outlookApplication.Session;
    Outlook.MAPIFolder contactFolder = outlookNs.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
    contactFolder.Items.Add += new NetOffice.OutlookApi.Items_ItemAddEventHandler(OnAddContact);
}

void OnAddContact(Outlook.ContactItem item)
{
    MessageBox.Show(item.FullName);
}
but it fails to compile on the line where the event handler is added:
No overload for 'OnAddContact' matches delegate 'NetOffice.OutlookApi.Items_ItemAddEventHandler' (CS0123)

I'm not even sure this is the right event, but it would be nice to get it compiled at least.
A handler for a new contact event can't be hard can it?

Thanks.
Jan 30, 2014 at 3:02 AM
void IDTExtensibility2.OnStartupComplete(ref Array custom)
{
  Outlook._NameSpace outlookNs = _outlookApplication.Session;
  Outlook.MAPIFolder contactFolder = outlookNs.GetDefaultFolder(Outlook.Enums.OlDefaultFolders.olFolderContacts);
  var contacts = (Outlook.Items)contactFolder.Items;

  //Add is a method
  //contactFolder.Items.Add += new NetOffice.OutlookApi.Items_ItemAddEventHandler(OnAddContact);

  //ItemAddEvent is an event
  contacts.ItemAddEvent += new Outlook.Items_ItemAddEventHandler(OnAddContact);
}

void OnAddContact(NetOffice.COMObject item)
{
  var contact = (Outlook.ContactItem)item;
  MessageBox.Show(contact.FullName);
}

Notes

  • I suppose you initialize _outlookApplication variable in IDTExtensibility2.OnConnection method.
  • This code tracks new contacts only in default contacts folder. It is possible to have multiple (including nested) contact folders.
Marked as answer by zasky on 1/30/2014 at 1:34 AM
Jan 30, 2014 at 9:34 AM
Thanks artnib, all working now.

I did realise that Add was a method and that it was wrong, but its always better to post some code and I just couldn't work out how to access the event. You gave me the crucial cast:
var contacts = (Outlook.Items)contactFolder.Items;
No amount of Googling pointed me to that.

Thanks also for the reminder about the default contacts folder, I guess I'll have to work out how to enumerate the other folders and add similar events which seems messy, unless you happen to know of an easier way to capture events for all new contacts.