WPF 主窗口在关闭子窗口后置于后台

问题描述 投票:0回答:2

我开发了一个示例 WPF 项目。
这是主窗口的代码隐藏:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Telerik.Windows.Controls;

namespace MainWindowInBackground
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Window l_hostWindow = new Window()
            {
                Owner = System.Windows.Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Content = "Test"
            };

            l_hostWindow.Show();

            Window l_hostWindow2 = new Window()
            {
                Owner = System.Windows.Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Content = "Test 2"
            };

            l_hostWindow2.Show();
            l_hostWindow2.Close();

            //MessageBox.Show(this, "MessageBox", "MessageBox", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
        }
    }
}

当用户单击按钮时:

  1. 创建并显示窗口 R1
  2. 创建并显示窗口 R2
  3. R2窗口已关闭

我已执行以下操作:

  • 我已经启动了该应用程序。操作后截图:

enter image description here

  • 我已经点击了按钮。显示 R1 窗口。操作后截图:

enter image description here

  • 我已经关闭了R1窗口。主窗口已自动置于背景中。操作后截图:

enter image description here

有人可以解释一下为什么主窗口被自动置于后台以及如何避免它吗? 预先感谢您的帮助

wpf window
2个回答
6
投票

无法告诉你为什么它被发送到后台,但让它保持在前台并获得焦点的方法是使其成为子窗口的所有者,并在子窗口关闭时调用父窗口的

Window.Focus()
方法。 ..

public ChildWindow()
{
    InitializeComponent();
    Owner = Application.Current.MainWindow;
}

private void ChildWindow_OnClosed(object sender, WindowClosedEventArgs e)
{
    if (Owner == null) return;
    Owner.Focus();
}

0
投票

在子窗口中设置

Owner
将阻止用户将父窗口带到前台(父窗口可以获得焦点,但子窗口在相交时不会移到父窗口后面)..

如果您想在某个窗口关闭时将主窗口带到前台,您可以在一处完成

private void ChildWindow_OnClosed(object sender, WindowClosedEventArgs e)
{
    Application.Current.MainWindow?.Activate(); // Or Focus()
}
© www.soinside.com 2019 - 2024. All rights reserved.