2012-09-25 31 views
2

我有一個事件掛鉤到C#中的Microsoft Word文檔DocumentBeforeClose事件。MS Word文檔關閉前事件不會取消

this.Application.DocumentBeforeClose += 
       new MSWord.ApplicationEvents4_DocumentBeforeCloseEventHandler(Application_DocumentBeforeClose); 

如果某些邏輯是對的,我取消標誌設置爲true,那麼該文件將不會關閉。但是,雖然事件被觸發並且取消標誌設置爲true,但文檔仍然關閉。

這是一個錯誤?

+0

只是走開了一下。從邏輯上講,當您將「取消」設置爲false時,這並不意味着「取消」功能不應該起作用,並且將其設置爲真應該使其起作用?你說你做了什麼,你設置取消爲真。 – Steven

+1

@Steven設置取消爲真意味着「是的,請取消關閉事件」。如果Joe將取消設置爲true,但文檔關閉,則看起來有些錯誤。 – phoog

+0

@phoog啊,謝謝澄清。 – Steven

回答

2

我終於明白了。我還需要將事件處理程序掛接到實際的Word文檔(Microsoft.Office.Tools.Word.Document)對象。 (Tools.Word.Document和Interop.Word.Document給我頭疼......)

this.Application.DocumentBeforeClose += new Interop.Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(Application_DocumentBeforeClose); 

Application_DocumentBeforeClose(Interop.Word.Document document, ref bool Cancel) 
{ 
    // Documents is a list of the active Tools.Word.Document objects. 
    if (this.Documents.ContainsKey(document.FullName)) 
    { 
    // I set the tag to true to indicate I want to cancel. 
    this.Document[document.FullName].Tag = true; 
    } 
} 

public MyDocument() 
{ 
    // Tools.Office.Document object 
    doc.BeforeClose += new CancelEventHandler(WordDocument_BeforeClose); 
} 

private void WordDocument_BeforeClose(object sender, CancelEventArgs e) 
{ 
    Tools.Word.Document doc = sender as Tools.Word.Document; 

    // This is where I now check the tag I set. 
    bool? cancel = doc.Tag as bool?; 
    if (cancel == true) 
    { 
    e.Cancel = true; 
    } 
} 

如此以來,我所有的應用程序邏輯的應用類的代碼做的,我需要一種方法來表示我的myDocument中我想要取消關閉活動的課程活動。所以這就是爲什麼我使用標籤對象來保存標誌。