Find open forms in C # windows application

I use this function to close an existing form and open a new form.

If there is no exixting form, it throws an error.

Mistake:

Target: System.Object MarshaledInvoke (System.Windows.Forms.Control, System.Delegate, System.Object [], Boolean)

Message: Invoke or BeginInvoke cannot be called in the control until a window handle is created.

Stack: in System.Windows.Forms.Control.MarshaledInvoke (control call, delegation method, [] args object, boolean synchronous)

SO need to check the open form before closing the form to avoid errors. How?

    static public void NewMainForm(Form main, bool ClosePreviousMain)
    {
            if (main != null)
            {
                Global.ActiveForm = main.Text;
                if (ClosePreviousMain & MyContext.curMain != null)
                {
                    MyContext.curMain.FormClosed -= new FormClosedEventHandler(main_FormClosed);
                    //Need to check for any form active and then close the form.
                    MyContext.curMain.Invoke(new Action(MyContext.curMain.Dispose));
                }
                MyContext.curMain = main;
                MyContext.curMain.FormClosed += new FormClosedEventHandler(main_FormClosed);
                MyContext.curMain.ShowDialog();
            }
    }
+5
source share
4 answers
if (ApplicationFormStatus.CheckIfFormIsOpen("FormName")) 
{
// It means it exists, so close the form
}

 public bool CheckIfFormIsOpen(string formname)
        {

            //FormCollection fc = Application.OpenForms;
            //foreach (Form frm in fc)
            //{
            //    if (frm.Name == formname)
            //    {
            //        return true;
            //    }
            //}
            //return false;

            bool formOpen= Application.OpenForms.Cast<Form>().Any(form => form.Name == formname);

            return formOpen;
        }

, - LINQ.

+5

this part of the code looks for an existing instance of the form if exists, simply displays it, and if it does not create an instance from it

       `foreach (Form form in Application.OpenForms)
        {
            if (form.GetType() == typeof(myMainform))
            {
                form.Activate();
                form.Show();
                this.Close();
                return;
            }
        }

        myMainform m = new myMainform();
        m.Show();`
+2
source

If you know the name of the form, you can also do the following:

var frm = Application.OpenForms.Cast<Form>().Where(x => x.Name == "MyForm").FirstOrDefault();
if (null != frm)
{
    frm.Close();
    frm = null;
}
+1
source

All Articles