C# 如何检查表单是否打开,如果打开关闭表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13445155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:34:20  来源:igfitidea点击:

How to check if form is open, if open close form?

c#winformsform-control

提问by Edwin Torres

How do I check if a form is open, and if it is open to close the form?

如何检查表单是否已打开,以及是否已打开以关闭表单?

I tried the following, testing out some code but it keep saying the form is not open even when I know it is:

我尝试了以下操作,测试了一些代码,但它一直说即使我知道表单没有打开:

 foreach(Form a in Application.OpenForms) 
 {
     if (a is YouLikeHits_Settings) 
     {
         // About form is open
         MessageBox.Show("form open");
         break;
     }
     // About form is not open...
     MessageBox.Show("form not open");
     break;
 }

采纳答案by Sergey Berezovskiy

Application.OpenFormscontains opened forms. If form in this collection, then it is opened. Otherwise it is not opened (possibly closed).

Application.OpenForms包含打开的表单。如果表单在此集合中,则将其打开。否则它不会打开(可能关闭)。

if (Application.OpenForms.OfType<YouLikeHits_Settings>().Any())
    MessageBox.Show("Form is opened");
else
    MessageBox.Show("Form is not opened");

回答by Nitin...

This will work sure

这肯定会起作用

            if (Application.OpenForms.OfType<frm_YouLikeHits_Settings>().Any())
            {
                Application.OpenForms.OfType<frm_YouLikeHits_Settings>().First().Close();
            }
            frm_YouLikeHits_Settings f1= new frm_YouLikeHits_Settings();
            f1.MdiParent = this;
            f1.Show();

回答by John G

try
{
    if (Application.OpenForms.OfType<talkForm>().Any())
    {
        talkForm frm = new talkForm();
        frm.Close();
        MessageBox.Show("Form is opened");
    }
    else
    {
        talkForm frm = new talkForm();
        frm.Show();
        MessageBox.Show("Form is not opened");
    }
}
catch(Exception ex)
{

}