0

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.

  • Does this answer your question? [Bring a window to the front in WPF](https://stackoverflow.com/questions/257587/bring-a-window-to-the-front-in-wpf) – aepot Nov 28 '20 at 23:10
  • If you have parent and child windows remember to assign the parent window to the Owner property of the child window. – Thinko Nov 28 '20 at 23:16
  • @aepot I have updated the question and added a video, hopefully this should help – johnstart2312 Nov 29 '20 at 10:50
  • @johnstart2312 did you try setting `TopMost` as suggested in the linked answers? – aepot Nov 29 '20 at 10:56

1 Answers1

0

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();
        }
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Max
  • 68
  • 8