0

so I have this program, and I want to prevent it from opening multiple times but can seem to get the hang of it =/

    private void button1_Click(object sender, EventArgs e)
    {


        if (forge.Checked)
        {
            successfully_injected openForm = new successfully_injected();
            openForm.Show();
            this.Close();
        }
        else if (!forge.Checked)
        {
            select_option openForm = new select_option();
            openForm.Show();
        }

    }

I only want to be able to click the button once and then it stops showing more windows, but the result I get right now is that I can click it and it will just keep opening windows every time I click so yeh =/

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
  • 3
    Unrelated: There is no use to check `if condition else if not condition` condition is either true or false and if it is true, it's not false.... `if(forge.Checked) {...} else {...}`is enough. – Fildor May 27 '19 at 13:45
  • You should have `select_option openForm = new select_option();` and `successfully_injected openForm = new successfully_injected();` at form level... and only show them on button click. – Chetan May 27 '19 at 13:46
  • 1
    Is this WinForms? Or WPF? – Steve May 27 '19 at 13:46
  • https://stackoverflow.com/a/3023745/17034 – Hans Passant May 27 '19 at 13:55
  • Note that OpenForms [is not reliable](https://stackoverflow.com/questions/3751554/application-openforms-count-0-always/3751748#3751748). – Hans Passant May 27 '19 at 13:59

3 Answers3

0

You could check the collection OpenForms from the Application object

if(forge.Checked)
{
   successfully_injected openForm = Application.OpenForms.OfType<successfully_injected>().FirstOrDefault();
   if(openForm == null)
       openForm = new successfully_injected();
   openForm.Show();
}
else
{
   select_option openForm = Application.OpenForms.OfType<select_option>().FirstOrDefault();
   if(openForm == null)
       openForm = new select_option();
   openForm.Show();
}
this.Close();
Steve
  • 213,761
  • 22
  • 232
  • 286
0

You should define your main form as a Singleton. This way there is only 1 instance that is usable throughout the entire application, thus also preventing multiple forms showing up.

A good example of this can be found in another question that's similar to yours here.

K.Warrens
  • 35
  • 8
0

give the owner to the new window

    successfully_injected openForm = new successfully_injected();
        Owner = openForm;
        Hide();
        openForm.Show();

Now the new window has the owner and you can simply close it and it works