2011-10-08 85 views
1

我已創建單實例應用程序。它接受命令行參數並處理它們。如果應用程序已經運行並且打開了一些對話框(打開的文件或消息框)。現在,如果我嘗試傳遞命令行參數,我需要檢查是否顯示對話框。所以我添加了這個代碼。檢測是否有對話框打開

 if (!Application.Current.MainWindow.IsActive) 
     { 

      Application.Current.MainWindow.Activate(); 
     } 

     if (Keyboard.FocusedElement != null) 
     { 
     // If focused element is not null it means no other dialog is shown. 
     // safe to go. 
     } 

理想狀,如果聚焦元件不爲空,則意味着焦點是內部窗口,並且顯示沒有其它對話框。

在正常情況下,當窗口未最小化時,此代碼正常工作。但是如果窗口最小化,那麼條件失敗,因爲鍵盤焦點不在窗口中。

您是否找到任何通用的解決方案?我可以通過在每個對話框前添加標誌來實現這一點。但我有超過10個對話框。將來我可能會添加更多的對話框。

謝謝

+0

請發表您的代碼啓動對話框 – Paparazzi

+0

MessageBox.Show(Application.Current.MainWindow,的 「Hello World」); –

+0

創建多個MessageBox的代碼是什麼? – Paparazzi

回答

5

很古老的問題,但我最近面臨類似的問題。 這是我如何解決它:

public static bool IsAnyModalOpened() 
{ 
    return Application.Current.Windows.OfType<Window>().Any(IsModal); 
} 

public static bool IsModal(this Window window) 
{ 
    var fieldInfo = typeof(Window).GetField("_showingAsDialog", BindingFlags.Instance | BindingFlags.NonPublic); 
    return fieldInfo != null && (bool)fieldInfo.GetValue(window); 
} 
+0

這是一個破解。我想知道是否有更好的方法。 –