Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading