How would I check if a form is open?

Morgenstern 40 Reputation points
2023-05-01T23:49:59.8766667+00:00

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;
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,819 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,401 Reputation points
    2023-05-02T01:19:04.1366667+00:00

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

  2. Jiale Xue - MSFT 44,231 Reputation points Microsoft Vendor
    2023-05-02T03:21:19.9233333+00:00

    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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.