简体   繁体   中英

C# Word AddIn BeforeClose Event disappear

Hi from few days I'm fighting with BeforeClose Event. Problem is when I'm opening more documents. For example: I'm opening 4 new documents, every single document in NewDocument Event attache BeforeClose Event to Document like that :

var vstoDoc = Globals.Factory.GetVstoObject(this.Application.ActiveDocument);
vstoDoc.BeforeClose += new System.ComponentModel.CancelEventHandler(ThisDocument_BeforeClose);

Now I'm trying to close it so I'm closing Doc4 after Doc2 and now is problem because Doc1 still have BeforeClose Event but Doc3 not. So if I close Documents descending starting from last it's work fine. But if I close for example Doc1 as first the rest don't have BeforeClose Event. I don't have idea what's happening.

I'm not sure why it's behaving the way it does, but I've never seen in the documentation that you can attach events to documents using GetVstoObject. It might have to do with re-using the same object (vstoDoc) for each document, rather than assigning each to a separate object. If you created a class to generate these objects, then kept them in a collection, it might work better. HOWEVER

My recommendation is to use the Application-level DocumentBeforeClose event that's available to your VSTO application-level Add-in. That will trigger automatically for ALL documents that are closed while the Add-in is running. If you want to track certain ones, add a Custom Document Property or a DocumentVariable to them when they're created (NewDocument) or opened (DocumentOpen) that you can check when DocumentBeforeClose is triggered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM