Name
Handles Keyword
Syntax
Handlesname.event
-
name(required; String literal) The name of the class or object whose event the subroutine is handling
-
event(required; String literal) The name of the event that the subroutine is handling
Description
Defines a procedure as the event handler for a particular event
Rules at a Glance
The
Handlerkeyword is used to define event handlers for events trapped by an object defined with theWithEventskeyword.The
Handleskeyword can only be used with a procedure declaration, since an event handler must be a procedure rather than a function.The
Handleskeyword must be placed on the same line as, and at the end of, a procedure declaration.
Example
In a Windows application, the following definition appears in the declarations section of the Form1 class module:
Public WithEvents Button1 As Button
The Button1 object is then instantiated with a line of code like the following in the New subroutine or another initialization routine:
Me.Button1 = New Button
The Button1 object’s Click event can then be handled with a event handler like the following:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
MsgBox("Hello, World!")
End SubProgramming Tips and Gotchas
The
WithEventsandHandlesare designed to define event handlers at compile time. If you want to define event handlers dynamically at runtime, use theAddHandlerandRemoveHandlerstatements.By convention, event handlers take the form
objectname ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access