在c#windows应用程序中找到打开的表单

Anu*_*uya 9 c# windows winforms

我正在使用此功能关闭现有表单并打开一个新表单.

如果没有exixting表单,则会抛出错误.

错误:

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

消息:在创建窗口句柄之前,无法在控件上调用Invoke或BeginInvoke.

Stack:at System.Windows.Forms.Control.MarshaledInvoke(Control caller,Delegate method,Object [] args,Boolean synchronous)

因此,在关闭表单之前需要检查是否打开任何表单以避免错误.怎么样?

    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();
            }
    }
Run Code Online (Sandbox Code Playgroud)

Jul*_*lin 23

您可以使用Application.OpenForms集合.


Tej*_* MB 7

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;
        }
Run Code Online (Sandbox Code Playgroud)

我已经将两个方法粘贴一个简单的方法,第二个方法是LINQ.


Ven*_*l M 7

如果您知道表单的名称,您也可以这样做:

var frm = Application.OpenForms.Cast<Form>().Where(x => x.Name == "MyForm").FirstOrDefault();
if (null != frm)
{
    frm.Close();
    frm = null;
}
Run Code Online (Sandbox Code Playgroud)