0

I'am trying to detect opened forms in C# with this code;

if ((Application.OpenForms["Form1"] as Form1) != null)
{
    Application.OpenForms["Form1"].Close();
}

But my form has ShowInTaskBar = false and my code does not work.

How can I detect opened or closed forms if the form has property ShowInTaskBar = false?

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91

3 Answers3

3

What you need to do is got application level get forms can do as follows.

FormCollection openforms = Application.OpenForms;
foreach (Form form in openforms)
{
    if (form.Name == "frmsomething")
    {
        form.Close();
    }
    // Whatever you want do with individual forms in form object
}
Mustafa Özçetin
  • 1,893
  • 1
  • 14
  • 16
charithsuminda
  • 341
  • 2
  • 9
  • thank you for quicky replay but it is not working. if form property is ShowInTaskBar=false; openforms count is 0.i changed property ShowInTaskBar=true; openforms count is 1. but this solution does not work for me – Onur Külekci Dec 02 '17 at 10:52
  • I test it , its fine even with ShowInTaskBar=false, Share more detail of your problem maybe its from somewhere else... – Arman.Salehi Dec 02 '17 at 11:00
  • So maybe here is your problem : https://stackoverflow.com/questions/3751554/application-openforms-count-0-always – Arman.Salehi Dec 02 '17 at 11:16
  • Good work in researching the problem and discovering the duplicate. @OnurKülekci if you set the ShowInTaskBar after the creation of the form you get that bug – Steve Dec 02 '17 at 11:39
  • @Steve Thanks! Solved my problem. your comment is solved my problem! – Onur Külekci Dec 02 '17 at 12:02
0

It seems the issue is that ShowInTaskBar = false causes .NET to ignore the form in the list of opened forms. You can however set the form not to show in task bar by using Windows API as described int this SO answer.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
0
Form2 form
private void btn1_Click(object sender, EventArgs e)
    {
        form = new Form2();
        form.Show();
    }

private void btn2_Click(object sender, EventArgs e)
    {
        if(form != null && !form.IsDisposed){
              form.Close();
        }
    }