检测是否打开了任何对话框

010*_*011 1 wpf wpf-controls

我创建了单实例应用程序.它接受命令行参数并处理它们.如果应用程序已在运行,则会打开一些对话框(打开的文件或消息框).现在,如果我尝试传递命令行参数,我需要检查是否显示对话框.所以我添加了这段代码.

        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.
        }
Run Code Online (Sandbox Code Playgroud)

理想就好了,如果聚焦元素不为null则表示焦点在窗口内,没有显示其他对话框.

在正常情况下,当窗口未最小化时,此代码可正常工作.但如果窗口最小化,则条件失败,因为键盘焦点不在窗口中.

你找到任何通用的解决方案吗?我可以通过在每个对话框之前添加标志来实现此目的.但我有10个以上的对话框.将来我可能会添加更多对话框.

谢谢

Mat*_*att 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);
}
Run Code Online (Sandbox Code Playgroud)