Prevent duplicate MDI children forms

前端 未结 7 688
攒了一身酷
攒了一身酷 2020-12-09 11:47

Is there a way to prevent the opening of a certain form within an MDI container if that said form is already opened?

相关标签:
7条回答
  • 2020-12-09 12:24

    A method can be implemented using Generics (below C# and VB.net options), which can be useful if different MDI Forms need to be opened.

    C#

    private void OpenMDI<T>(bool multipleInstances)
        where T : Form, new()
    {
        if (multipleInstances == false)
        {
            // Look if the form is open
            foreach (Form f in this.MdiChildren)
            {
                if (f.GetType() == typeof(T))
                {
                    // Found an open instance. If minimized, maximize and activate
                    if (f.WindowState == FormWindowState.Minimized)
                    {
                        f.WindowState = FormWindowState.Maximized;
                    }
    
                    f.Activate();
                    return;
                }
            }
        }
    
        T newForm = new T();
        newForm.MdiParent = this;
        newForm.Show();
    }
    

    Use it as follows (indicate false in multipleInstances to prevent them)

    OpenMDI<Form2>(false);
    

    VB.NET

    Public Sub Open_MDI(Of T As {New, Form})(bMultipleInstances As Boolean)
        If bMultipleInstances = False Then
            For Each f As Form In Me.MdiChildren
                If TypeOf f Is T Then
                    If (f.WindowState = FormWindowState.Minimized) Then
                        f.WindowState = FormWindowState.Maximized;
                    End If
    
                    f.Activate()
                    Exit Sub
                End If
            Next
        End If
    
        Dim myChild As New T()
        myChild.MdiParent = Me
        myChild.Show()
    End Sub
    

    Use it as follows (indicate False for bMultipleInstances to prevent them)

    Open_MDI(Of Form2)(False)
    
    0 讨论(0)
提交回复
热议问题