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

限于喜欢 提交于 2019-12-01 03:46:50

问题


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;
 }

回答1:


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

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



回答2:


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();



回答3:


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)
{

}


来源:https://stackoverflow.com/questions/13445155/how-to-check-if-form-is-open-if-open-close-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!