Test to see if a form is open, in this case close it. Checking for Form2.
var childForms = Application.OpenForms.OfType<Form2>().ToList();
if (childForms.Count() == 1)
{
childForms.FirstOrDefault()!.Close();
}
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi, I need to check if a form is open so I can close it because if I write
frmNewNote.instance.Invoke(new MethodInvoker(frmNewNote.instance.Hide));
and the form was not open it will give me this error: 'Delegate to an instance method cannot have null 'this'.' In the form frmNewNote form I wrote
public static frmNewNote instance;
...
instance = this;
Test to see if a form is open, in this case close it. Checking for Form2.
var childForms = Application.OpenForms.OfType<Form2>().ToList();
if (childForms.Count() == 1)
{
childForms.FirstOrDefault()!.Close();
}
Good Day @Morgenstern ,
After checking the code from your previous question, it appears that frmNewNote
is the window you create via the main window.
frmNewNote.instance.Invoke(new MethodInvoker(frmNewNote.instance.Hide));
There is no problem with the code itself.
But when you finish running, you could close the current window directly.
For your main form, frmopen
should use Hide()
and Show()
to operate and should not be closed directly when running the opened form, otherwise you cannot return to the main form correctly. (Just a suggestion.)
For checking whether a form is opened or closed.
If your open means "visible", you can determine it by judging the Visible
property. True
means open.
The Visible property will be set to false
when you use the Hide()
method.
If you want to determine whether the target window is released, you can use the IsDisposed
property to determine it.
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.