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?
Asked
Active
Viewed 929 times
2 Answers
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
-
thanks. If its already launched, can I close it through this way? – crazy novice Nov 21 '13 at 16:09
-
Actually i am using .net 3.5. Seem like it cannot be utilized in my code. Any other ways of doing it? – crazy novice Nov 21 '13 at 16:14
-
i guess i can always loop through the Application.OpenForms collection and compare its type with that of my non-modal form type – crazy novice Nov 21 '13 at 16:21
-
2Are you just missing a `using System.Linq;` ? – sgmoore Nov 21 '13 at 16:22
-
@PaulSnow yep, sorry was busy. And yes, sgmoore is right - LINQ is available since .NET 3.5 – Sergey Berezovskiy Nov 21 '13 at 16:25
-
Is there a way to do a helper function out of this? How do i parameter the type/class of the form? – John Thompson Nov 16 '22 at 08:10
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