检查表单是否已打开的最佳方法?

时间:2017-09-04 14:16:13

标签: c# winforms

我正在制作一个具有以下功能的程序:

  • 如果打开表单 soanthao ,则程序会将新标签页添加到soanthao表单的tabControlEx控件中

  • 如果没有打开表单 soanthao ,程序将首先加载soanthao表单,然后程序将新的标签页添加到soanthao表单的tabControlEx控件中。

应该注意tabControlEx控件没有标签页。

我已使用此代码:

soanthao st = new soanthao();
            bool opened=false;
            FormCollection fc = Application.OpenForms;

            foreach (Form frm in fc)
            {
                if (st == frm)
                {
                     opened = true;
                }
            }
            if (opened==false)
            {

                RichTextBox rtb = new RichTextBox();
                TabPage tb = new TabPage();
                tb.Text = textBox1.Text;
                st.tabControlEx1.TabPages.Add(tb);
                rtb.Parent = tb;
                rtb.Dock = DockStyle.Fill;
                st.Show();
                this.Hide();
                opened = false;
            }
            if (opened == true)
            {

                RichTextBox rtb = new RichTextBox();
                TabPage tb = new TabPage();
                tb.Text = textBox1.Text;
                st.tabControlEx1.TabPages.Add(tb);
                st.tabControlEx1.SelectTab(st.tabControlEx1.TabCount - 1);
                rtb.Parent = tb;
                rtb.Dock = DockStyle.Fill;
                this.Hide();
            }

但问题是程序总是打开一个新的soanthao表单,即使已经打开soanthao表单。

1 个答案:

答案 0 :(得分:3)

我建议使用 Linq ;如果你想知道是否已经打开soanthao

using System.Linq;

... 

soanthao st = Application
  .OpenForms
  .OfType<soanthao>()
  .LastOrDefault(); // If many soanthao are opened, take the last one

if (st != null) {
  // "st" is the soanthao instance opened
}
else {
  // no opened soanthao instance, let's create it
  st = new soanthao();

  ...

  // ...and show up
  st.Show(); 
}

您的方法中的错误位于st == frm行:

foreach (Form frm in fc)
{
    // You actually check if "st" instance is opened and it's not, but created only
    if (st == frm) // <- Error is here
    {
        opened = true;
    }
}

修改你的方法:

bool opened = false;

foreach (Form frm in Application.OpenForms) {
  // Do we have ANY soanthao form opened?
  if (frm is soanthao) { // ... i.e. if an opened form is of type soanthao?
    opened = true;
    break;
  } 
} 

...