Warm tip: This article is reproduced from serverfault.com, please click

Close Window on Deactivated and Focus on Parent Window WPF

发布于 2020-11-28 21:34:54

In my WPF Project, I have two Windows and from the main parent Window I call the child like so:

PARENT

ChildWindow win = new ChildWindow();
win.Owner = this /* (Parent window) */;
win.Show();

CHILD

private void Window_Deactivated(object sender, EventArgs e)
{
    this.Close();
    owner.Activate();
    // Also tried: owner.Focus();
}

And I want it so that when the user clicks on the Parent window, it closes the child window and focuses on the parent. I have made a Deactivated event on the child which does Close(); but on clicking the parent window, it closes the window but hides the parent one as well so it is not focused, but under all other applications. How can I make it so that it doesn't? I have tried having a owner.Activate(); after it is closed but same thing happens.

This is a small video of what is happening: https://vimeo.com/485043728. I would like to get the same effect when clicking on another window (where the parent window is visible) but when the user clicks back to the parent window, it hides it.

Questioner
johnstart2312
Viewed
0
21k 2020-12-16 22:54:44

You can do something like this for your desired result.

MainWindow.xaml

<Window x:Class="StackOverflow.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:StackOverflow"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Height="50" Width="100" Content="Open Child" Click="Button_Click"/>
    </Grid>

MainWindow.xaml.cs

using System.Windows;

namespace StackOverflow
{
    public partial class MainWindow : Window
    {
        private Window _child;

        public MainWindow()
        {
            InitializeComponent();
            _child = new Window();
            _child.LostKeyboardFocus += _child_LostFocus;
        }

        private void _child_LostFocus(object sender, RoutedEventArgs e)
        {
            _child.Hide();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _child.Show();
        }
    }
}