Find the open forms in c# windows application

前端 未结 4 1678
时光说笑
时光说笑 2020-12-17 16:55

I am using this function to close existing form and open a new form.

If there is no exixting form, it throws error.

Error :

Target : System.Object

相关标签:
4条回答
  • 2020-12-17 17:35

    If you know the name of the form you can as well do like this :

    var frm = Application.OpenForms.Cast<Form>().Where(x => x.Name == "MyForm").FirstOrDefault();
    if (null != frm)
    {
        frm.Close();
        frm = null;
    }
    
    0 讨论(0)
  • 2020-12-17 17:49
    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;
            }
    

    I have pasted the two methods one simple one and the second one is the LINQ.

    0 讨论(0)
  • 2020-12-17 17:51

    You can use the Application.OpenForms collection.

    0 讨论(0)
  • 2020-12-17 17:54

    this part of code searches for existing instance of a form if exists just shows it , and if not creates an instance of 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();`
    
    0 讨论(0)
提交回复
热议问题