首页 > 解决方案 > WPF - 为什么窗口突然失去焦点?

问题描述

设想

考虑以下场景:您在 WPF 中启动一个应用程序。

  1. 主窗口打开(非模态)Window1(由 拥有MainWindow
  2. 您将焦点更改为其他窗口(例如,Visual Studio)
    • 在其他应用程序具有焦点的情况下,您按下一个按钮Window1
    • Window1 显示一个消息框
  3. 你关闭消息框

效果:您的主窗口突然低于您在第二步中选择的窗口。

图片:

步骤1

步骤1

第2步

第2步

第 3 步

第 3 步

第4步

第4步

资料来源:

主窗口.xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel Orientation="Vertical">
            <TextBox />
            <Button Content="Open window" Click="Button_Click" />
        </StackPanel>
    </Grid>
</Window>

主窗口.xaml.cs

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

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Window1 window1 = new Window1();
            window1.Owner = this;

            window1.Show();
        }
    }
}

Window1.xaml

<Window x:Class="WpfApp1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="Window1" Height="450" Width="800" ShowInTaskbar="False">
    <Grid>
        <Button Click="Button_Click"/>
    </Grid>
</Window>

Window1.xaml.cs

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

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Test");

            Close();
        }
    }
}

问题

从另一个窗口关闭消息框后如何在主窗口中保持焦点?

标签: c#wpfxamlfocus

解决方案


推荐阅读