代码之家  ›  专栏  ›  技术社区  ›  Javed Akram

限制MDI应用程序中的窗口实例数

  •  4
  • Javed Akram  · 技术社区  · 14 年前

    我想限制用户在MDI应用程序中创建表单的多个实例。

    如果打开该窗体的一个实例,则必须获得焦点。如果不是新实例,则必须创建它。

    我该怎么做?

    3 回复  |  直到 14 年前
        1
  •  5
  •   codingbadger    14 年前

    你可以这样做。

    创建静态方法:

    public static Form IsFormAlreadyOpen(Type FormType)
    {
        foreach (Form OpenForm in System.Windows.Forms.Application.OpenForms)
        {
            if (OpenForm.GetType() == FormType)
                return OpenForm;
        }
    
        return null;
    }
    

    然后在创建子窗体时。

    frmMyChildForm frmChild1;
    
     if ((frmChild1 = (frmMyChildForm)IsFormAlreadyOpen(typeof(frmMyChildForm))) == null)
        { //Form isn't open so create one
            frmChild1= new frmMyChildForm ();
    
        }
       else
        { // Form is already open so bring it to the front
           frmChild1.BringToFront();
    
         }
    
        2
  •  0
  •   james_bond    14 年前

    也许这样可以帮到你

    Form frmToCreate;
    String strClassName=typeof(FormToCreate).Name
    frmToCreate = GetForm(strClass);
    if(frmToCreate == null)
    {
        //create the form here
    }
    frmToCreate.MdiParent = this; //supposing you are inside of the mainwindow (MDI window)
    frmToCreate.Visible = true;
    //other code goes here
    

    GetForm是这样的

    public Form GetForm(String type)
    {
        int i;
        Form[] children = this.MdiChildren; //or mdiwindow.MdiChildren
    
        for (i = 0; i < children.Length; i++)
        {
            if (children[i].GetType().Name == type)
            {
                return children[i];
            }
        }
        return null;
    }
    

    如果只是玩玩的问题 MdiChildren 属性。

        3
  •  -1
  •   Kalle    14 年前

    您可以使用单例模式方法,并让窗体具有一个实例成员变量,用于跟踪它是否已初始化。

    http://en.wikipedia.org/wiki/Singleton_pattern