0

I have a button click event which will pop up a form. How do I check if an existing form is already present before creating one and showing it?

here is my code

private void Button_Click(object sender, RoutedEventArgs e) {

        Wizard wizard = new Wizard();

        if (wizard.IsVisible)
        {

        }
        else
        {
            wizard.Show();
        }
    }

the code here does not work as a new pop up wizard (form) is created everytime i click on the button from another window.

Ka Res
  • 311
  • 2
  • 3
  • 17
P. Kwong
  • 61
  • 2
  • 9
  • Near-duplicate: https://stackoverflow.com/questions/3861602/how-to-check-if-a-windows-form-is-already-open-and-close-it-if-it-is?noredirect=1&lq=1 – peeebeee Jan 23 '18 at 11:35
  • It would be more user-friendly to disable the Button when the form is shown and re-enable it when the form is closed. – Clemens Jan 23 '18 at 11:38

1 Answers1

0

Either use ShowDialog and make it modal

Or use the reference reference to wizard or a bool flag to make the check. Make sure if you use a reference to set it null afterwards

bool isOpen;

...

public void click()
{     
    if (!isOpen)
    {
        // do something
        wizard = new Wizard();
        wizard.Closing += (sender, args) =>
                            {
                                isOpen = false;
                            };
        isOpen = true;
        wizard.Show();
    }
...

Or as noted in comments. Set the button Enabled property false to protect from further hits

Enabled = false; 
TheGeneral
  • 79,002
  • 9
  • 103
  • 141