About Me

My photo
I'm currently the CTO for Hedgehog Technology a business dedicated to delivering Cloud based productivity solutions in Logistics

Thursday, January 24, 2008

Hooking up to an Item Changed Event in VSTO

After last night's mossig meeting and my Outlook/VSTO presentation someone asked me about the following scenario:
"I want to capture the fact that a user changes an email address in the Outlook contacts list and call into a custom Web Service to update my LOB-system recording that change." For those that have used the Outlook object model before that is probably not a difficult task, for those new to Outlook and tempted by VSTO to give Office Integration a go it may not be so obvious so I decided to write a little bit of demo-code in C# to show how to setup the event handler, I'll leave the actual call to a Web Service or updating a database using .net classes up to the student as an exercise ;-). Start by creating a new Outlook Addin project, open ThisAddIn.cs and add the code below.


.....
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
.....
public partial class ThisAddIn
{
Outlook.MAPIFolder contactfolder;
Outlook.Items items; // This on is important, keep the reference at the addin level, a local var in the startup method will get garbage collected and the events will stop firing.

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Outlook.NameSpace ns;
ns = this.Application.GetNamespace("MAPI");
contactfolder = ns.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts);
items = contactfolder.Items;
items.ItemChange +=
new Outlook.ItemsEvents_ItemChangeEventHandler(ItemChanged);

}
private void ItemChanged( object item )
{
Outlook.ContactItem contact;
contact = (Outlook.ContactItem)item;
// This is were you do your thing......
System.Windows.Forms.MessageBox.Show(contact.Email1Address);
}
.....


The same is available for ItemAdd, for delete events you would have to hookup an ItemAdd to the DeletedItems folder.

1 comment:

Bijay Kumar said...

Thanks Boss!!! My Events were not firing. After I follow ur code Its works for me !!! Thanks a lot

Bijaya Kumar Sahoo
http://www.fewlines4biju.com
India