AnsweredAssumed Answered

Unwiring events in an Add-in in preparation for shutting down ArcMap

Question asked by jbailey.spatialbridge on Oct 1, 2014
Latest reply on May 29, 2015 by jbailey.spatialbridge

I've created an ArcMap Add-in that responds to the AfterDraw event from the active view. When shutting down ArcMap, I was receiving an InvalidComObjectException from ESRI.ArcGIS.Carto.IActiveViewEvents_EventProvider.Finalize(). My guess was that, while I was wiring events to delegates in my code, I wasn't unwiring them prior to shutdown. So, I wrote the following code that seems to work correctly (at least, no more exceptions are thrown on shutdown):

 

public class MyCommand : ESRI.ArcGIS.Desktop.AddIns.Button 
{
     public MyCommand()
     {
         ArcMap.Events.ActiveViewChanged += Events_ActiveViewChanged;
         ArcMap.Events.BeforeCloseDocument += Events_BeforeCloseDocument;
     }

     private void Events_ActiveViewChanged()
     {
         // wire events on the current active view
         IActiveViewEvents_Event activeViewEvents = (IActiveViewEvents_Event)ArcMap.Document.FocusMap;
         // unwire the current handler
         activeViewEvents.AfterDraw -= new IActiveViewEvents_AfterDrawEventHandler(OnActiveViewEventsAfterDraw)
         // wire the handler to the current active view's event
         activeViewEvents.AfterDraw += new IActiveViewEvents_AfterDrawEventHandler(OnActiveViewEventsAfterDraw)
     }

     private bool Events_BeforeCloseDocument
     {
         // unwire event handlers from the document being closed
         IActiveViewEvents_Event activeViewEvents = (IActiveViewEvents_Event)ArcMap.Document.FocusMap;
         activeViewEvents.AfterDraw -= new IActiveViewEvents_AfterDrawEventHandler(OnActiveViewEventsAfterDraw)
         return false;
     }

     private void OnActiveViewEventsAfterDraw(IDisplay display, esriViewDrawPhase drawPhase)
     {
         // code here in response to the AfterDraw event
     }

     private override void Dispose(bool disposing)
     {
         // unwire add-in events
         ArcMap.Events.ActiveViewChanged -= Events_ActiveViewChanged;
         ArcMap.Events.BeforeCloseDocument -= Events_BeforeCloseDocument;
         base.Dispose(disposing);
     }
 }

 

This seems to work, but it doesn't seem very robust, and I'm not sure that it's event correct.

 

Does anyone have any experience in doing this who could offer some advice?

 

Thanks,

 

Jon.

Outcomes