Reputation: 1817
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?
Upvotes: 1
Views: 1056
Reputation: 39122
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();
}
}
}
Upvotes: 0
Reputation: 236208
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();
}
Upvotes: 4