Jack
Jack

Reputation: 16724

How to set events in Microsoft.Office.Interop.Word namespace?

I tried

var wordApp = new Microsoft.Office.Interop.Word.Application();
var doc = wordApp.Documents.Open(FileName);
wordApp.Visible = true;

   ((Microsoft.Office.Interop.Word.ApplicationEvents4_Event)wordApp.Quit) += new ApplicationEvents4_QuitEventHandler(delegate
                    {
                        MessageBox.Show("word closed!");
                    });

But I get:

Cannot convert method group 'Quit' to non-delegate type 'Microsoft.Office.Interop.Word.ApplicationEvents4_Event'. Did you intend to invoke the method?


Microsoft.Office.Interop.Word._Application.Quit(ref object, ref object, ref object)' 
and non-method 'Microsoft.Office.Interop.Word.ApplicationEvents4_Event.Quit'. Using method group.

I did the cast because of warning, but was not solved. And I don't know how to solve this error. Thanks in advance.

Upvotes: 0

Views: 3706

Answers (1)

Hans Passant
Hans Passant

Reputation: 941327

You misplaced a parenthesis in the cast expression, you don't want to cast Quit. Proper syntax is:

((Microsoft.Office.Interop.Word.ApplicationEvents4_Event)wordApp).Quit += ...

Perhaps you can stay out of trouble easier by using the using directive so you feel less need for cramming expressions and can write more readable code:

using Word = Microsoft.Office.Interop.Word;
...

    var wordApp = new Word.Application();
    var doc = wordApp.Documents.Open(FileName);
    wordApp.Visible = true;
    var events = (Word.ApplicationEvents4_Event)wordApp;
    events.Quit += delegate {
        MessageBox.Show("word closed!");
    };

Upvotes: 1

Related Questions