2

I am trying to write an addin that notices when an appointment is saved and does some data. For that, I need to check whether, when the active inspector is closed, the item is saved or not.

My problem is this: when trying to bind a WriteEvent-listener to the current item in the FormRegionShowing-method, I need the ActiveInspector to event get the current item. However, when getting the ActiveInspector there, it is null, probably, because that method is called before the active inspector is actually active.

When trying to bind it in the FormRegionClosed-method, however, the write event never fires. So, how do I know when an AppointmentItem is actually saved by the user?

EDIT: I managed to bind the write event in the FormRegionShowing-method, but it still won't fire:

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

    Outlook.AppointmentItem currentItem = (Outlook.AppointmentItem)this.OutlookItem;

    currentItem.Write += new Outlook.ItemEvents_10_WriteEventHandler(currentItem_Write);

    currentItem.AfterWrite += new Outlook.ItemEvents_10_AfterWriteEventHandler(currentItem_AfterWrite);

    MessageBox.Show("added handlers");

}

void currentItem_AfterWrite(){
    MessageBox.Show("item has been saved");
}

void currentItem_Write(ref bool Cancel){
    MessageBox.Show("item being saved");
}
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
arik
  • 28,170
  • 36
  • 100
  • 156

1 Answers1

4

You need to move Outlook.AppointmentItem to a class level variable. In COM, the RCW will be garbage collected when the function goes out of scope. If you want to use events with Office, you need to be sure to review the eventing model. Also see related SO post.

private Outlook.AppointmentItem currentItem; // keep events from getting GC'd

private void ADDIN_NAME_FormRegionShowing(object sender, System.EventArgs e){
    currentItem = (Outlook.AppointmentItem)this.OutlookItem;
    currentItem.Write += new Outlook.ItemEvents_10_WriteEventHandler(currentItem_Write);
    currentItem.AfterWrite += new Outlook.ItemEvents_10_AfterWriteEventHandler(currentItem_AfterWrite);
}
Community
  • 1
  • 1
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173
  • But using this code, the effect is that every time I open and edit the event, the number of Write and AfterWrite event is incremented by one. The MessageBox in the test is shown N times, being N, the amount of times the item was opened and edited! :( – Cesar Vega Oct 20 '14 at 14:50
  • @CesarVega - sounds like `currentItem` is getting persisted between event views. You need to disconnect the events after the Form Region closes. Take a look at [`FormRegionClosed`](http://msdn.microsoft.com/en-us/library/microsoft.office.tools.outlook.formregioncontrol.formregionclosed.aspx) and disconnect the `Write`/`AfterWrite` events (*via operator overloading -=*). – SliverNinja - MSFT Oct 20 '14 at 18:02
  • Thanks SliverNinja, that was it! – Cesar Vega Oct 20 '14 at 20:40