Campl3r Campl3r - 3 months ago 30
C# Question

Single Instance Window WPF not working

I only want to have a single instance of my Window in WPF.

My code in the window:

public static bool IsOpen { get; private set; }
private void Window_Loaded(object sender, RoutedEventArgs e)
{
IsOpen = true;
}

private void Window_Unloaded(object sender, RoutedEventArgs e)
{
IsOpen = false;
}


My code in the open function

if (MyWindow!= null)
{
if (MyWindowName.IsOpen)
{
MyWindow.Activate();
}
else
{
MyWindow.Close();
MyWindow= null;
}
}
if (MyWindow!= null) return;

MyWindow= new MyWindowName();
MyWindow.Show();
MyWindow.Activate();


But I am able to open many instances of the window if I click fast 3-5 times.

Thanks

Answer

There will be a delay between you opening with window with the show command (which will then process the message queue allowing the processing of the other clicks) and then the firing of the windows loaded event.

An extremely quick and dirty fix would be to move the IsOpen assignment to just before the show command, you could also use a return inside the if to remove the need for a second check.

if (MyWindow!= null)
{
    if (MyWindowName.IsOpen)
    {
        MyWindow.Activate();
        return;
    }
    else
    {
        MyWindow.Close();
        MyWindow= null;
    }
}

MyWindow= new MyWindowName();
MyWindow.IsOpen = true;
MyWindow.Show();
MyWindow.Activate();