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

3696
2
10-01-2014 06:05 AM
JonathanBailey
Occasional Contributor III

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.

0 Kudos
2 Replies
DuncanHornby
MVP Notable Contributor

Can you reformat your code, it is very difficult for others to read when its all on one line.

0 Kudos
JonathanBailey
Occasional Contributor III

Done.

0 Kudos