vbnet引用事件的简单介绍( 二 )


' The event member that is of type AlarmEventHandler.
'
Public Event Alarm As AlarmEventHandler
' The protected OnAlarm method raises the event by invoking
' the delegates. The sender is always this, the current instance
' of the class.
'
Protected Overridable Sub OnAlarm(e As AlarmEventArgs)
RaiseEvent Alarm(Me, e)
End Sub
' This alarm clock does not have
' a user interface.
' To simulate the alarm mechanism it has a loop
' that raises the alarm event at every iteration
' with a time delay of 300 milliseconds,
' if snooze is not pressed. If snooze is pressed,
' the time delay is 1000 milliseconds.
'
Public Sub Start()
Do
nrings += 1
If stopFlag Then
Exit Do
Else
If _snoozePressed Then
System.Threading.Thread.Sleep(1000)
If (True) Then
Dim e As New AlarmEventArgs(_snoozePressed, nrings)
OnAlarm(e)
End If
Else
System.Threading.Thread.Sleep(300)
Dim e As New AlarmEventArgs(_snoozePressed, nrings)
OnAlarm(e)
End If
End If
Loop
End Sub
End Class
' The WakeMeUp class has a method AlarmRang that handles the
' alarm event.
'
Public Class WakeMeUp
Public Sub AlarmRang(sender As Object, e As AlarmEventArgs)
Console.WriteLine((e.AlarmText + ControlChars.Cr))
If Not e.SnoozePressed Then
If e.NumRings Mod 10 = 0 Then
Console.WriteLine(" Let alarm ring? Enter Y")
Console.WriteLine(" Press Snooze? Enter N")
Console.WriteLine(" Stop Alarm? Enter Q")
Dim input As String = Console.ReadLine()
If input.Equals("Y") Or input.Equals("y") Then
Return
Else
If input.Equals("N") Or input.Equals("n") Then
CType(sender, AlarmClock).SnoozePressed = True
Return
Else
CType(sender, AlarmClock).Stop = True
Return
End If
End If
End If
Else
Console.WriteLine(" Let alarm ring? Enter Y")
Console.WriteLine(" Stop Alarm? Enter Q")
Dim input As String = Console.ReadLine()
If input.Equals("Y") Or input.Equals("y") Then
Return
Else
CType(sender, AlarmClock).Stop = True
Return
End If
End If
End Sub
End Class
' The driver class that hooks up the event handling method of
' WakeMeUp to the alarm event of an Alarm object using a delegate.
' In a forms-based application, the driver class is the
' form.
'
Public Class AlarmDriver
Public Shared Sub Main()
' Instantiates the event receiver.
Dim w As New WakeMeUp()
' Instantiates the event source.
Dim clock As New AlarmClock()
' Wires the AlarmRang method to the Alarm event.
AddHandler clock.Alarm, AddressOf w.AlarmRang
clock.Start()
End Sub
End Class
End Namespace
请教下vb.net 什么时候用事件,raiseevent和直接调用函数有多大区别,谢谢raiseevent
在合适的地方或时机触发事件,以执行已与该事件绑定的所有函数 。
事件一旦被触发 , 将执行所有与该事件有关的函数,同一个事件执行的函数代码可以完全不同,开发者可以通过一个事件去做不同的事情 。
——
开发一个按钮类,并定义好一个点击事件 , 通过用户点击按钮类来触发事件,最后创建两个按钮的实例:按钮1和按钮2 。
点击按钮1 , 点击事件执行弹出一个消息框的代码 。
点击按钮2 , 点击事件执行打开一个文件的代码 。
若点击按钮不触发事件,而是执行某一定义好的函数paly , 在点击后,按钮1和按钮2将只能执行相同的函数play 。
浅见,通过一个事件可以做不同的事情,通过一个函数只可以做该函数规定的事情,除非每次都去修改函数 , 如果拥有该事件的类\控件是别人开发的 , 在别人没有提供源代码的情况之下,那根本不可能修改 。

推荐阅读