Search code examples
c#wpfwindow

How to get focus to selected window if it exists in WPF C#


I have application with "About" button. When it is clicked, I want to open a new window with credits. But If the window is already open, I want only bring it to focus (first plan), instead of opening next instance. The first part, to prevent opening multiple windows is easy:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        var existingWindow = Application.Current.Windows.OfType<About>().Any();
        if (!existingWindow)
        {
            About p = new About();
            p.Show();
        }
    }

So first I check if any windows of type About exist, and if it is false I create new instance and show it. But how to implement the second part? I mean else statement if the window About is already open, to bring it to the first plan?


Solution

  • I think what you're looking for is the Activate method. Here's how I would write it:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var existingWindow = Application.Current.Windows.OfType<About>().FirstOrDefault();
        if (existingWindow != null)
        {
            existingWindow.Activate();
        }
        else
        {
            About p = new About();
            p.Show();
        }
    }
    

    I'm using FirstOrDefault() instead of Any() to get the first window of type About or null if no such window exists. Then I check if existingWindow is not null and call Activate() or make a new one accordingly.