2012-06-14 39 views
4

我在執行特定任務之前檢查Word是否仍然可見。在關閉可見性檢查關閉Word 2010後,問題是執行只會凍結。 2007年不會發生。檢查Word是否可見時執行凍結

//Initializing Word and Document 

While(WordIsOpen()) 
{ 
} 

//Perform Post Close Tasks 

public bool WordIsOpen() 
{ 
    if(MyApp.Application.Visible)//Execution just freezes at this line after Word is not visible 
      return true; 
    else 
      return false; 
} 

任何人都看過這個問題嗎?

有沒有更好的方法來檢查?

+0

什麼類型'MyApp'? –

+0

Microsoft.Office.Interop.Word.Application MyApp – ExceptionLimeCat

+0

這是否僅在調試會話期間發生?我想知道是否winword.exe被連接到VS,它導致它阻止MyApp.Application.Visible。如果您在未經調試的情況下運行項目會發生什麼 – Dai

回答

3

我的建議是申報定點標誌:從那裏

private bool isWordApplicationOpen; 

當初始化你Application例如,訂閱其Quit事件,並重置標誌:

MyApp = new Word.Application(); 
MyApp.Visible = true; 
isWordApplicationOpen = true; 
((ApplicationEvents3_Event)MyApp).Quit +=() => { isWordApplicationOpen = false; }; 
// ApplicationEvents3_Event works for Word 2002 and above 

然後,在你的循環,只需檢查標誌是否設置:

while (isWordApplicationOpen) 
{ 
    // Perform work here.  
} 

編輯:既然你只需要等待Word應用程序被關閉,下面的代碼可能更適合:

using (ManualResetEvent wordQuitEvent = new ManualResetEvent(false)) 
{ 
    Word.Application app = new Word.Application(); 

    try 
    { 
     ((Word.ApplicationEvents3_Event)app).Quit +=() => 
     { 
      wordQuitEvent.Set(); 
     }; 

     app.Visible = true; 

     // Perform automation on Word application here. 

     // Wait until the Word application is closed. 
     wordQuitEvent.WaitOne(); 
    } 
    finally 
    { 
     Marshal.ReleaseComObject(app); 
    } 
} 
+0

任何想法什麼類型的事件引發事件句柄需要? – ExceptionLimeCat

+0

事件委託是['ApplicationEvents4_QuitEventHandler'](http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.applicationevents4_quiteventhandler.aspx),它不接受參數並返回void。 – Douglas

+0

您可以在應用程序結束時處理'.Quit',避免完全旋轉等待。 –