1

My application launches a non-modal dialog on a button click. If user clicks on that button again, I would like to do a check if that form is already running and wonder if its possible?

crazy novice
  • 1,757
  • 3
  • 14
  • 36

2 Answers2

4

You can use Application.OpenForms Property

if (Application.OpenForms.OfType<YourNonModalFormType>().Any())
   // one is already opened

If you want to close this form:

var form = Application.OpenForms.OfType<YourNonModalFormType>().FirstOrDefault();
if (form != null)
{
    // launched
    form.Close();
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

Another approach is to manually declare a variable to track your form instance:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private Form2 f2 = null;

    private void button1_Click(object sender, EventArgs e)
    {
        if (f2 == null || f2.IsDisposed)
        {
            f2 = new Form2();
            f2.Show();
        }
        else
        {
            f2.Close();
        }
    }

}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40