子窗口在第三个窗口上使用ShowDialog后,主窗口在其他应用程序的窗口后面消失

dia*_*ler 14 c# wpf dialog window modal-dialog

我注意到WPF应用程序中这种非常奇怪的行为.

我有一个MainWindow,使用Show()来自显示App.OnStartup.说MainWindow可以打开(非模态)SubWindow,也可以使用Show().SubWindowOwner设置为MainWindow.

何时SubWindow关闭,MainWindow再次可见(好).

某些操作可能会导致SubWindow打开第三个窗口作为模式对话框,使用ShowDialog()(Owner设置为SubWindow).当该模态对话框在a的生命周期中至少打开并关闭一次时SubWindow,就会发生奇怪的事情.

关闭后SubWindow,MainWindow不会进入视野.相反,无论随机窗口后面 MainWindow映入眼帘.任何人都可以向我解释为什么会发生这种情况,以及如何解决它?

模态对话框是使用正常Window显示还是使用显示ShowDialog()的消息框没有区别MessageBox.Show().


这是一些重现这个的最小代码.在visual studio中创建一个新的WPF应用程序,并将其粘贴到预先生成的MainWindow.xaml.cs中

然后,按键盘上的一个键只打开一个窗口,关闭它,按预期行为.按两个键,关闭两个键,然后第一个窗口在Visual Studio后面(推测).

public MainWindow()
{
    InitializeComponent();
    this.PreviewKeyDown += (sender, e) =>
    {
        if (this.Owner is MainWindow)
        {
            // we're the SubWindow

            MessageBox.Show("I am a modal dialog");

            // code below produces the exact same behavior as the message box

            //var dialog = new MainWindow();
            //dialog.Owner = this;
            //dialog.ShowDialog();
        }
        else
        {
            // we're the initial MainWindow created by App.
            var subWindow = new MainWindow();
            subWindow.Owner = this;
            subWindow.Show();
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 10

This is a pretty annoying WPF bug, I never did find the flaw in the code that causes it but there's a heckofalot of "gotta figure this out" comments in the source code that deals with focusing. Just a workaround, a less than ideal one, you can solve it by explicitly giving the focus to the owner when the window is closing. Copy/paste this code in your SubWindow class;

    protected override void OnClosing(System.ComponentModel.CancelEventArgs e) {
        base.OnClosing(e);
        if (!e.Cancel && this.Owner != null) this.Owner.Focus();
    }
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,我们在大约 5 年前开发的普通 WinForms (.NET 2) 应用程序中看到了这个错误。我今天刚刚在一个新项目 (.NET 4.5) 中再次遇到它。我似乎记得错误取决于“Show()”嵌套 2-deep 或更深。看起来其他人也遇到过([这里](http://www.pcreview.co.uk/forums/vbulletin-2005-windows-app-goes-back-z-order-after-dialog-box- clo-t3140486.html) 和 [here](http://web1.codeproject.com/Messages/1813163/Application-Goes-to-Back-of-ZOrder-after-cloasing-.aspx));如果我记得我们使用了@Hans 建议的解决方法。 (2认同)