我不知道怎么写,所以标题可能看起来有点奇怪。我有一个 VB.NET MDI Winform 应用程序。在这个应用程序中,当我单击菜单项时,会打开一个子窗口。为了处理必须打开的子窗口,我的 ToolStripMenuItem_Click 事件中有 case 语句。问题在于,在每个案例项目中,代码几乎相同。所以我想知道是否有可能拥有一个通用功能,以便代码变得更具可读性。
例子:
Case "mnuPrint"
Dim ChildWindowFound As Boolean = False
If Not (MdiChildren.Length.Equals(0)) Then
For Each ChildWindow As Form In MdiChildren
If ChildWindow.Name.Equals("Form1") Then
ChildWindow.Activate()
ChildWindowFound = True
End If
Next
End If
If Not ChildWindowFound Then
Dim childForm As New Form1()
childForm.Name = "Form1"
childForm.MdiParent = Me
childForm.Show()
End If
Case "mnuSearch"
Dim ChildWindowFound As Boolean = False
If Not (MdiChildren.Length.Equals(0)) Then
For Each ChildWindow As Form In MdiChildren
If ChildWindow.Name.Equals("Form2") Then
ChildWindow.Activate()
ChildWindowFound = True
End If
Next
End If
If Not ChildWindowFound Then
Dim childForm As New Form2()
childForm.Name = "Form2"
childForm.MdiParent = Me
childForm.Show()
End If
如您所见,代码几乎相同,但形式不同,这里的 Form1 和 Form2 是不同的,但当然可以是许多不同的形式。我正在谈论的功能看起来像:
Public Sub OpenNewForm(ByVal frm As Form, ByVal parent As Form, ByVal singleInstance As Boolean)
Dim ChildWindowFound As Boolean = False
If Not (parent.MdiChildren.Length.Equals(0)) Then
For Each ChildWindow As Form In parent.MdiChildren
If ChildWindow.Name.Equals(frm.Name) Then
ChildWindow.Activate()
ChildWindowFound = True
End If
Next
End If
If Not ChildWindowFound Then
Dim childForm As New Form
childForm.Name = frm.Name
childForm.MdiParent = Me
childForm.Show()
End If
End Sub
这不起作用,因为我将参数(前两个)作为 Form-type 传递,例如它应该是 Form1 和 ParentForm,而不是 Form。我认为这是可能的,只是不知道从哪里开始。可能正在使用反射或什么?
更新:
根据给出的答案,我想出了这个工作正常的代码:
'Code contributed by Rod Paddock (Dash Point Software)
'www.dashpoint.com
'Dim oForm As Form = ObjectFactory.CreateAnObject("MyApplication.frmTwo")
'oForm.Show()
Public Shared Function CreateAnObject(ByVal ObjectName As String) As Object
Dim Assem = [Assembly].GetExecutingAssembly()
Dim myType As Type = Assem.GetType(ObjectName.Trim)
Dim o As Object = Nothing
Try
o = Activator.CreateInstance(myType)
Catch oEx As TargetInvocationException
MessageBox.Show(oEx.ToString)
End Try
Return o
End Function
Public Shared Sub ActivateChildWindow(ByVal frmName As String, ByRef ParentMDIWindow As Form)
Dim ChildWindowFound As Boolean = False
With ParentMDIWindow
If Not (.MdiChildren.Length.Equals(0)) Then
For Each ChildWindow As Form In .MdiChildren
If ChildWindow.Name.Equals(frmName) Then
ChildWindow.Activate()
ChildWindowFound = True
End If
Next
End If
End With
If Not ChildWindowFound Then
Dim childForm As Form = CreateAnObject(frmName)
childForm.Name = frmName
childForm.MdiParent = ParentMDIWindow
childForm.Show()
End If