j0057
j0057

Reputation: 922

Handling events from Word using dynamic com interop from C#

From Silverlight 4, it's pretty easy to start Word and let the user do something:

dynamic word = System.Runtime.InteropServices.Automation.CreateObject("Word.Application");
word.Visible = true;
word.Documents.Open("test.doc");

MS Word exposes a Quit event[1]. I'd like to handle this event, but for the life of me I can't figure out how. I tried to do this:

public delegate void WordQuitEventHandler(object sender, ref bool cancel);
public event WordQuitEventHandler OnQuit;
private void WordOnQuit(dynamic sender, ref bool cancel)
{
    if (OnQuit != null)
    {
        OnQuit(this, ref cancel);
    }
}

and then do

word.Quit = WordOnQuit;

or

word.Quit += WordOnQuit;

But it's not possible to assign the delegate for WordOnQuit to the dynamic object word.Quit. So how to capture this event?

[1] http://msdn.microsoft.com/en-us/library/aa211898(v=office.11).aspx

Upvotes: 2

Views: 2080

Answers (2)

EightyOne Unite
EightyOne Unite

Reputation: 11795

Just to be complete, the one you're looking for is...

AutomationEvent quitEvent = AutomationFactory.GetEvent(word,"Quit");
quitEvent.EventRaised += new EventHandler<AutomationEventArgs>(quitEvent_EventRaised);

Of course, you could inline the callback should you wish.

Also, I've found that this event can be a little flakey. Most of the time it fires...most of the time :-)

HTH.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500185

I haven't tried this, but it might work:

word.Quit += new WordQuitEventHandler(WordOnQuit);

Basically the compiler doesn't know what type you want to convert the method group to at the moment - the code above should give it enough information.

Upvotes: 1

Related Questions