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

C# 如何在Microsoft.Office.Interop.Word命名空间中设置事件?,c#,ms-word,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_QuitEve

我试过了

但我得到:

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.
也许您可以通过使用using指令更轻松地避免麻烦,这样您就不需要死记硬背表达式,并且可以编写更可读的代码:

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

谢谢你救了我一天。祝你今天过得愉快。
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!");
    };