Handles Keyword


Handles Keyword

Syntax

     Handles name.event 


name (required)

The name of the object with the event that the procedure is handling


event (required)

The name of the event member that the procedure is handling

Description

The Handles statement defines a procedure as the event handler for a particular class or type event.

Usage at a Glance

  • The Handles keyword is used to define event handlers for events trapped by an object defined with the WithEvents keyword.

  • The Handles keyword can only be used with a Sub procedure declaration, since an event handler must be a procedure rather than a function.

  • The Handles keyword must be on the same logical line as the procedure declaration.

  • A single Handles keyword can be followed by multiple comma-delimited event enTRies. This is done when a single event handler is used for multiple events.

  • The WithEvents and Handles keywords are designed to define event handlers at compile time. If you want to define event handlers dynamically at runtime, use the AddHandler and RemoveHandler statements.

  • By convention, event handlers take the form objectname_eventname. For example, the default event handler name for the Click event of an object named Button1 is Button1_Click. Although this convention is traditional and in common use, you are not required to follow it.

Example

If you add a command button to a new form, the form initialization code generated by Visual Studio includes the following statement:

     Friend WithEvents Button1 As System.Windows.Forms.Button 

The WithEvents keyword allows the events of this control to be processed by event handlers. The default procedure template used to handle this button's Click event looks like the following:

     Private Sub Button1_Click(ByVal sender As System.Object, _           ByVal e As System.EventArgs) Handles Button1.Click        ' ----- Custom code goes here.     End Sub 

The Handles clause in this code is what links Button1's Click event with the event handler code.

Version Differences

  • The Handles keyword is new to VB under .NET. In VB 6, the link between an object and its event handler was handled automatically and transparently by Visual Basic, based on the name of the event-handling procedure.

  • Visual Basic 2005 includes a new Custom Event feature that gives the developer more control over the lifetime of an event.

See Also

WithEvents Keyword




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

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