2012-06-09 40 views
0

我試圖如何在Microsoft.Office.Interop.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

您在演員表達式中放錯了圓括號,您不想演員退出。正確的語法是:

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

謝謝!你已經救了我的一天。祝你有個愉快的一天。 – Jack

相關問題