behzad razzaqi
behzad razzaqi

Reputation: 1511

How can i check form is open in c# windows application?

I want to write a simple c# windows application for this plan:
when then form load timer starts, check and show any another form,i have two forms,form one start timer 1 and timer 1 start form 2 with this code:

ShowALARM frm = new ShowALARM();
frm.Show();
frm.listBox1.Items.Add(x);


up code call with timer method,with per call that code,open new form!,i want to check to see if form is open, however, if false then run the new form.how can i solve that?thanks.

Upvotes: -1

Views: 459

Answers (1)

gzaxx
gzaxx

Reputation: 17600

You can get all open forms with code Application.OpenForms. To find particular form is open you can do this Application.OpenForms.OfType<Form1>().Any() where From1 is form you are looking for.

One piece of advice - do not write code like this: frm.listBox1.Items.Add(x); as you are breaking SoC (separation of concerns). One form should not know much about any other. Much better is to create a method on targeted form like AddItem(object x) and call it from other forms.

Code sample:

protected void TimerTickMethod()
{
   if (!IsShowALARMFormOpened())
   {
      ShowALARM frm = new ShowALARM();
      frm.Show();
   }
}

protected bool IsShowALARMFormOpened()
{
    return Application.OpenForms.OfType<ShowALARM>().Any();
}

Upvotes: 1

Related Questions