Adding Events

You can add events to your class to indicate that objects created from this class can raise the events you've added.

1. Add the code in Listing 3.8 to your Sentence class. This code adds an event statement and replaces the UpperCase method.

Listing 3.8. Creating an event for a class Public Event CaseChanged() Public Sub UpperCase()

TextValue = TextValue.ToUpper() RaiseEvent CaseChanged()

End Sub

2. Replace the code in the Startup event handler of ThisDocument with the code in Listing 3.9 so that a message box is shown when the event is raised.

You can create an event handler for the CaseChanged event by declaring the variables for the Sentence objects with the WithEvents keyword, as shown in Listing 3.9. This code also adds a method that handles the OnChanged event for the Sentence1 and

Sentence2 classes. Notice that the Sentence_ChangeCase method lists both Sentencel.CaseChanged and Sentence2.CaseChanged in the Handles clause.

Listing 3.9. Displaying a message box when an event is raised

WithEvents Sentence1 as New Sentence() WithEvents Sentence2 As New Sentence( _ "This is my first sentence.")

Private Sub ThisDocument_Startup(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Startup

Sentence1.Text = "This is my first sentence. " Sentence1.UpperCase()

Me.Paragraphs(1).Range.InsertAfter( _ Sentence1.Text & Sentence2.Text)

End Sub

Sub Sentence_CaseChange() Handles Sentence1.CaseChanged, _ Sentence2.CaseChanged

MsgBox("Case changed.")

End Sub

3. Press F5 to run the code.

Only one message box is displayed because only Sentence1 called the UpperCase method, which raised the CaseChange event. If you add code to call UpperCase on Sentence2, the event will be raised on both objects, and therefore two messages will be displayed.

0 0

Post a comment