VB.NET中,在訪問窗體之前,你必須進行窗體
實例化,然后才能打開,如:Dim frm1 As New Form1' frm1.MdiParent = Me ' 定義MDI子窗體frm.Show() '打開窗體如果在項目中有多處代碼訪問同一窗體,都這樣的話,則會創建出
VB.NET中,在訪問窗體之前,你必須進行窗體
實例化,然后才能打開,如:
Dim frm1 As New Form1
' frm1.MdiParent = Me ' 定義MDI子窗體
frm.Show() '打開窗體
如果在項目中有多處代碼訪問同一窗體,都這樣的話,則會創建出不同的實例。如重防止重復打開MDI子窗體的實例呢?下面的代碼可以幫你完成:
Dim frm1As New Form1
CheckForm(frm1, "Form1")
'*****************************************************************************'*過程名稱:CheckForm
'*參數說明:MDIChildForm需檢測的窗體;MDIChildFormName 檢測窗體的名字
'*功能說明:首先檢測是否有MDI子窗體,如果沒有,則創該MDI子窗體的窗體實例
'* 如果有,則檢測當中有沒有其窗體實例,有則激活;沒有則創建其窗體實例
'*****************************************************************************
Private Sub CheckForm(ByVal MDIChildForm As Form, ByVal MDIChildFormName As String)
If Me.MdiChildren.Length < 1 Then
'如果沒有任何一個MDI子窗體,則創該MDI子窗體的窗體實例
ShowForm(MDIChildForm )
Exit Sub
Else
Dim x As Integer
Dim frmyn As Boolean
For x = 0 To (Me.MdiChildren.Length) - 1
Dim tempChild As Form = CType(Me.MdiChildren(x), Form)
If tempChild.Name = MDIChildFormName Then
frmyn = True
'檢測到有該MDI子窗體,設為TRUE 并退出循環
Exit For
Else
frmyn = False
End If
Next
If frmyn = False Then
'在打開的窗體中沒檢測到則新建
ShowForm(tempForm)
Else
'在打開的窗體中檢測到則激活
Dim MDIChildFrm As Form = CType(Me.MdiChildren(x), Form)
MDIChildFrm .Activate()
End If
End If
End Sub
'**************************************************
'*過程名稱:ShowForm
'*參數說明:MDIChildForm 需創建實例的窗體
'*功能說明:創建窗體實例
'**************************************************
Private Sub ShowForm(ByVal MDIChildForm As Form)
Dim MDIChildFrm As Form = MDIChildForm
MDIChildFrm.MdiParent = Me ' 定義MDI子窗體
MDIChildFrm.Show() '打開窗體
End Sub