就像 bodjo 说的,你有 [YourMDIForm].ActiveMDIChild 属性。
正如 Plutonix 所说,不清楚的是您的保存“按钮”在哪里。你的意思是:
第一种情况非常简单:使用您的 MDIParent 表单的 .ActiveMDIChild。
第二个可能需要一些有效的方法来指向一个实际的活动子窗体(类似于您尝试使用globalVar 的那个......有更好的方法来做到这一点。
顺便说一句,当您通过 .ActiveMDIChild 获取目标 MDIChild 时,您必须使用 Public、Friend 或 Protected 变量访问文本框。通常,表单中的控件是私有的。所以你可能不得不:
Public Class [YourMDIChildClassName]
' ...
' create a Public Property
Public ReadOnly Property ContentToSave() As String
Get
Return [YourTextBox].Text
End Get
End Property
' or make your textbox public in the Form design
Public [YourTextBox] As TextBox
' ... the one or the other, not both.
' ...
End Class
另一种访问“活动”MDIChild 的方法,假设您的所有 MDIChild 都是同一类的实例,是在您的 Child 类中创建一个静态(共享)属性:
Public Class [YourMDIChildClassName]
' ...
Private Shared _CurrentMDIChild As [YourMDIChildClassName] = Nothing
Public Shared ReadOnly Property CurrentMDIChild() As [YourMDIChildClassName]
Get
Return _CurrentMDIChild
End Get
End Property
' ...
End Class
并使用您尝试过的相同方法,但使用 .Activated 而不是 .Clicked
Public Class [YourMDIChildClassName]
' ...
Private Sub MyChildForm_Activated() Handles Me.Activated
_CurrenMDIChild = Me
End Sub
' And that's ALL this method SHOULD contain.
' If you try to add other activation tricks, like activating another Form,
' or firing up a DialogBox (worst case),
' everything will go WRONG and your application will hang in an endless loop !!!
' Be carefull when using .Activated.
' ...
End Class
然后您可以使用静态属性访问当前活动的 MDIChild :
[YourMDIChildClassName].CurrentMDIChild
' => Gives you directly a VALID instance of your MDI Child (or Nothing !)
' Then you can use in your MDI Parent :
If [YourMDIChildClassName].CurrentMDIChild IsNot Nothing Then
Dim TextToSave As String = [YourMDIChildClassName].CurrentMDIChild.ContentToSave
' ... save your text...
End If
但是,因为您创建了一个指向最后一个活动 MDIChild 的静态(共享)指针(有点,我知道它不是 C 中的指针) 每次关闭 MDIChild 表单时都必须更新此指针!
Public Class [YourMDIChildClassName]
' ...
Private Sub [YourMDIChildClassName]_FormClosing( _
sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If _CurrentMDIChild Is Me Then ' And "Me" is closing right now...
_CurrentMDIChild = Nothing
' We don't want memory leak or pointer to a Form that has been closed !
End If
End Sub
' ...
End Class
我们不应该创建处理子表单激活的自定义方式。 MDIParent.ActiveMDIChild 就是为了这个。然而,一旦我们想要访问最初不存在于System.Windows.Forms.Form 中的子表单的extended/custom/specific 属性,我们需要将MDIParent.ActiveMDIChild 转换为真正的Form 派生类型我们的 MDI 孩子。这是另一种方法,但只有我一个人:我不太喜欢铸件。始终将 IDE 设置为:
Option Explicit On
Option Strict On
Option Infer Off
Forms.Clicked ...这个事件(点击)真的存在吗?我知道.Click,但没有“点击”。无论如何:
Public Class [YourMDIChildClassName]
' ...
Private Sub MyChildForm_Clicked() Handles Me.Click
' This part is executed when you click INSIDE the Form,
' at a location where there is NO Control.
' If you click on a control, like a Textbox, a Picturebox, a Panel, etc
' this block IS NOT EXECUTED as you've clicked on a control,
' not on the Form !
End Sub
' ...
End Class