How to check if form is open, if open close form?
23,652
Solution 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");
Solution 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();
Author by
Edwin Torres
Updated on July 09, 2022Comments
-
Edwin Torres almost 2 years
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; }
-
Edwin Torres over 11 yearsWas I did was make a button which opens the form, then in another button I put in the code above, when I click it, it keeps saying, form is not open.
-
Edwin Torres over 11 yearsYour code worked to detect it being open :). Any way after it pops up with the message box that the form is open I can close that certain form?
-
Sergey Berezovskiy over 11 yearsYes, you can:
Application.OpenForms.OfType<YouLikeHits_Settings>().First().Close()
-
aminvincent over 8 yearsi have tried it but my certainly form open cannot be closed automaticly
-
aminvincent about 8 years@SergeyBerezovskiy i have same problem like this.. i tried your suggest code and it ran well when i show my form using
form1.show();
but when i tried useform1.showdialog();
the form cannot be closed. if any suggest for me i will say thanks so much -
Sergey Berezovskiy about 8 years@aminvincent I think you should create new question with all related to your problem information and code to reproduce issue.
-
aminvincent about 8 years@SergeyBerezovskiy thanks for your suggest,..finally i create new question and this the link that i created and that it solved: stackoverflow.com/questions/35471376/…
-
Juano almost 4 yearsMany thanks, it worked like a charm and exactly what you said and I needed :)