主窗体:
Public Event msg(ByVal i As Int16) '''首先定义一个事件
Dim i As Int16 '''定义一个变量
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
i += 1
RaiseEvent msg(i) '''激发事件
End Sub
Dim frm As Addition = Nothing '''从窗体
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If frm Is Nothing Then
frm = New Addition
frm.main = Me '''此处是应该注意的地方,一定要把从窗体定义的主窗体设置成此窗体,否则不会引发事件!
End If
'''上面定义从窗体的方法,可以避免多次实例化窗体
frm.Show()
End Sub
从窗体:
Public WithEvents main As main '''定义主窗体事件并执行
Private Sub main_msg(ByVal i As Short) Handles main.msg
Label1.Text = i
End Sub
1,以上方法是主窗体定义事件,然后触发,在从窗体执行的情况,需要注意的是frm.main=me
此句的意思是从窗体的触发事件是主窗体定义的
2,但是在现实应用中,通常都是从窗体内容发生变化,需要及时更新主窗体,此时代码有小小的变动,如下,
需要仔细看啊!
主窗体:
Public WithEvents add As Addition
Dim frm As Addition = Nothing
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If frm Is Nothing Then
frm = New Addition
Me.add = frm '''注意此处的区别
End If
frm.Show()
End Sub
Private Sub add_msg(ByVal i As Short) Handles add.msg
Label1.Text = i
End Sub
从窗体:
Public Event msg(ByVal i As Int16)
Dim i As Int16
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
i += 1
RaiseEvent msg(i)
End Sub