如何在Microsoft.Office.Interop.Word命名空间中设置事件?

时间:2012-06-09 15:40:58

标签: c# ms-word

我试过

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!");
                    });

但我明白了:

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.

由于警告,我做了演员,但没有解决。我不知道如何解决这个错误。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您在演员表达式中错误放置了一个括号,您不想强制退出。正确的语法是:

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

使用 using 指令可能会让您更容易避免麻烦,因此您不再需要填充表达式,并且可以编写更易读的代码:

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!");
    };