【问题标题】:Is there any other way to access open forms in C#?有没有其他方法可以在 C# 中访问打开的表单?
【发布时间】:2016-01-27 19:15:08
【问题描述】:
 Application.OpenForms["formname"];

还有其他方法可以访问打开的表单吗?我的应用程序虽然已打开,但没有看到此表单。我不知道为什么。

【问题讨论】:

  • 这个“formname”是打开表单的实例名还是打开表单的类名?也许您也可以在这里发布您的代码,尤其是与“formname”相关的代码
  • 你设置了表单的name吗?
  • OpenForms 集合包含什么?
  • 查看所有打开的表格:MessageBox.Show(String.Join(Environment.NewLine, Application.OpenForms.OfType<Form>().Select(form => form.Name)));你能找到所需的表格吗?
  • 不要忘记您创建的表单对象。 Or work around the bug.

标签: c# forms winforms


【解决方案1】:

获得一个开放的表格真的不需要一个名字。 你可以通过索引得到你想要的表格:

Form frm = Application.OpenForms[0] //Will get the main form
Form frm = Application.OpenForms[1] //Will get the first child

OpenForms 集合中的表单的排序方式与您创建它的方式相同

否则,另一种方法是保存对表单的引用,然后通过该引用访问它。

//Where you want to save the reference:
Form theForm;
//Where you create the form:
myClass.theForm = new MyForm();
//Where you want to get that form:
MessageBox.Show(myClass.theForm.Caption);

(myClass 是保存您对表单的引用的类,假设您从不同的类访问它)

(另外,看看你是否受到这个影响:Application.OpenForms.Count = 0 always

【讨论】:

  • OpenForms 集合中的表单的排序方式与您创建它的方式相同 这是否记录在案?
  • @nawfal 正如我们从源代码中看到的那样:referencesource.microsoft.com/#System.Windows.Forms/winforms/… 在表单 OnLoad 事件(使用 OpenFormsInternalAdd)上将一个表单添加到该集合中。因此,只要我们按顺序显示表单,就应该保证顺序。
【解决方案2】:

我建议您首先调试您的代码以检查您要加载的Form 实际名称是什么:

foreach (Form form in Application.OpenForms) {
    string name = form.Name; //check out this name!!
    //print, or anything else will do, you only want to get the name
    //note that you should be able to get any form as long as you get its name correct
}

然后,一旦您知道您的代码有什么问题,只需执行以下操作:

Form form = Application.OpenForms[name]; //use the same name as whatever is available according to your debug

获取您的form

要检查可能存在的错误,请参阅Hans Passant's Post

【讨论】:

    【解决方案3】:

    你必须先实例化一个Form。之后你就可以访问它了:

    Form1 formname = new Form1();
    Application.Run(formname);
    
    // access to form by formname.yourproperty
    

    【讨论】:

    【解决方案4】:

    要使用此属性访问表单,您的form 必须具有Name

    记住它不是实例名称,也不是文本形式:

      Form1 f1 = new Form1();    //not "f1" is the "Name"  
      f1.Text = "it is title of the form"; //neither "Text" is the "Name"
      f1.Name= "its the name"; //it is the "Name"
    

    示例:

    frm_myform form1 = new frm_myform(); 
    frm_myform.Name = "form1";
    

    【讨论】:

    • 我知道,不是文字。我使用表单名称,但 Application.openForms 既不返回 null 也不返回其他内容。
    • frm_myform form1=new frm_myform();
    • 那你就可以通过你的form1变量访问表单了吧?
    • 是的。我使用 form1 变量访问它。
    • @nrtn93 我要求提供完整的代码,因为在这一行中您没有设置表单的 Name 属性。这就是我提到的。
    猜你喜欢
    • 2011-08-06
    • 1970-01-01
    • 2022-01-23
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    相关资源
    最近更新 更多