2011-10-08 82 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

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