Defining and Raising Events

 <  Day Day Up  >  

A type declares an event in much the same way that it declares a subroutine.

 Class Button   Private X, Y As Integer   Public Event Click()   Public Event Moved(ByVal X As Integer, ByVal Y As Integer) End Class 

In this example, the Button class declares two events: a Click event that will be raised when the button is pressed and a Moved event that will be fired when the button is moved somewhere else on the screen. The Moved event has two parameters that represent the coordinates of where the button is being moved to. These parameters will be passed to any method that handles the event.

An event is raised by using the RaiseEvent statement, which has much the same syntax as a method invocation.

 Sub Move(ByVal X As Integer, ByVal Y As Integer)   Me.X = X   Me.Y = Y   ' Notify other types that we have moved.   RaiseEvent Moved(X, Y) End Sub 

This example moves the button to a new location and then raises the Moved event, passing in the new coordinates of the button.

One thing to keep in mind about events is that they are multicast ; this means that an event can be handled by more than one handler. In the following example, the same Click event is handled by two separate types.

 Class Form1   Public WithEvents Button1 As Button   Sub Clicked() Handles Button1.Click     ...   End Sub End Class Class Form2   Public WithEvents Button2 As Button   Sub Clicked() Handles Button2.Click     ...   End Sub End Class Module Test   Sub Main()     Dim f1 As Form1 = New Form1()     Dim f2 As Form2 = New Form2()     Dim b As Button = New Button()     f1.Button1 = b     f2.Button2 = b   End Sub End Module 

Because both f1 and f2 handle the Click event for the same instance of the Button class, when that button is clicked, both Form1.Clicked and Form2.Clicked will be called. The order in which the event handlers are called is determined by the .NET Framework at runtime.

 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net