どう表現したらいいのか分からないので、タイトルがおかしくなっているかもしれません。VB.NET MDI Winform アプリケーションがあります。このアプリでは、メニュー項目をクリックすると子ウィンドウが開きます。どの子ウィンドウを開く必要があるかを処理するために、ToolStripMenuItem_Click イベントに case ステートメントがあります。問題は、すべての case-item でコードがほぼ同じであることです。そのため、コードが読みやすくなるように一般的な機能を持たせることができるかどうか疑問に思っていました。
例:
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
パラメーター (最初の 2 つ) を Form-type として渡すため、これは機能しません。たとえば、Form ではなく、Form1 と ParentForm である必要があります。可能だと思いますが、どこから始めればよいかわかりません。リフレクションか何かを使用している可能性がありますか?
アップデート:
与えられた答えに基づいて、うまく機能しているこのコードを思いつきました:
'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