The following example uses events to count down seconds from 10 to 0. The code illustrates several of the event-related methods, properties, and statements, including the RaiseEvent statement.
The class that raises an event is the event source, and the methods that process the event are the event handlers. An event source can have multiple handlers for the events it generates. When the class raises the event, that event is raised on every class that has elected to handle events for that instance of the object.
The example also uses a form (Form1) with a button (Button1) and a text box (TextBox1). When you click the button, the first text box displays a countdown from 10 to 0 seconds. When the full time (10 seconds) has elapsed, the first text box displays "Done".
The code for Form1 specifies the initial and terminal states of the form. It also contains the code executed when events are raised.
To use this example, open a new Windows Application project, add a button named Button1 and a text box named TextBox1 to the main form, named Form1. Then right-click the form and click View Code to open the Code Editor.
Add a WithEvents variable to the declarations section of the Form1 class.
Private WithEvents mText As TimerState
Add the following code to the code for Form1. Replace any duplicate procedures that may exist, such as Form_Load, or Button_Click.
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Button1.Text = "Start"
mText = New TimerState
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
mText.StartCountdown(10.0, 0.1)
End Sub
Private Sub mText_ChangeText() Handles mText.Finished
TextBox1.Text = "Done"
End Sub
Private Sub mText_UpdateTime(ByVal Countdown As Double) _
Handles mText.UpdateTime
TextBox1.Text = Format(Countdown, "##0.0")
' Use DoEvents to allow the display to refresh.
My.Application.DoEvents()
End Sub
Class TimerState
Public Event UpdateTime(ByVal Countdown As Double)
Public Event Finished()
Public Sub StartCountdown(ByVal Duration As Double, _
ByVal Increment As Double)
Dim Start As Double = DateAndTime.Timer
Dim ElapsedTime As Double = 0
Dim SoFar As Double = 0
Do While ElapsedTime < Duration
If ElapsedTime > SoFar + Increment Then
SoFar += Increment
RaiseEvent UpdateTime(Duration - SoFar)
End If
ElapsedTime = DateAndTime.Timer - Start
Loop
RaiseEvent Finished()
End Sub
End Class
Press F5 to run the preceding example, and click the button labeled Start. The first text box starts to count down the seconds. When the full time (10 seconds) has elapsed, the first text box displays "Done".
Note: |
|---|
The
My.Application.DoEvents method does not process events in exactly the same way as the form does. To allow the form to handle the events directly, you can use multithreading. For more information, see Multithreading in Visual Basic.
|