I am currently developing a Vsto Word Addin in C#.
I am looking for an event that is fired every time a new document is created from a template and the document is fully loaded and displayed to the user.
I need this event to make adjustments to the header and footer of the document and to call up the document information using this line (Globals.ThisAddIn.Application.CommandBars.ExecuteMso(‘DocumentInformationShowHide’);).
I have already tested the ‘word.Application.DocumentChange’ event, which is fired too early, before the document is loaded and displayed to the user.
public async void Application_DocumentChange()
{
_logger.Info("Application_DocumentChange event triggered.");
ManipulateHeaderAndFooter();
Globals.ThisAddIn.Application.CommandBars.ExecuteMso("DocumentInformationShowHide");
}
This blocks Word completely for me when using DocumentChanged Event:
Thats why i need a Event that triggers later (after document is loaded and already displayed to the user) or another workaround for it.
Edit: I already tried using Application.NewDocument Event, but also this event triggers to early before the document is loaded and displayed to the user.
Here is my solution.
I used a combination of the events ApplicationEvents4_Event.NewDocument
, ApplicationEvents4_Event.DocumentOpen
and ApplicationEvents4_Event.DocumentChange
, each for different use cases. However, these events sometimes throw too early, so that certain methods such as opening the document information should not be executed directly. In this case, I have inserted a delay to counteract the problem and wait until the word document is fully loaded. (this is just a workaround)
await System.Threading.Tasks.Task.Delay(1000);
Important: In a Word AddIn, access to the synchronisation context after an await. If you want to access the COM object after the await, you must execute this code with synchronisation context.
Create synchronisation context (on startup)
if (SynchronizationContext.Current == null)
{
// Create a new UI context for the add-in because Office AddIns do not have one by default
SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
}
_syncContext = SynchronizationContext.Current;
Use synchronisation context after await:
_syncContext.Post(_ =>
{
// Operation that accesses the COM-Object
}, null);
At some point I had so many operations before the critical operation that I no longer needed to use the delay.