Title: The Creation, Use, and Consumption of Events with Microsoft Visual Basic .NET Zach Kramer Support Pr
1The Creation, Use, and Consumption of Events with
Microsoft Visual Basic .NETZach KramerSupport
ProfessionalDeveloper Support PSSMicrosoft
Corporation
2Objectives
- Examine the purpose of events
- Understand the handling of events
- Explore the creation of events
- Review the underlying pieces that are used to
construct an event - Explore some advanced topics about events
3Agenda
- Purpose of Events
- Consuming Events
- Creating and Raising Events
- Review of Events from ILDASM
- Advanced Event Concepts
- Event Example
- Summary
4Purpose of Events
- Programming paradigm
- A way of controlling the flow of application
- Occur the way life does
- Something occurs and the application reacts
- Programs choose to handle or ignore events
- Allows alerts without polling
- Avoid linear programming
- Communication of the status during a long-running
operation
5Consuming EventsHandlers
- Objects that raise events must have those events
connected to handlers. - Handlers are methods that are called when events
occur. - Multiple handlers can be connected for one event.
- Handler methods can be connected to multiple
events.
6Consuming Events (2)Declare an Instance of an
Event Source
- To be an event source, you must declare the
object WithEventsFriend WithEvents Button1 As
New Button - The object must expose at least one event to be
declared WithEvents. - WithEvents enables an object to be an event
source.
7Consuming Events (3) Creating a Handler Function
- Determine the correct method signature
- Using the object browser
- Create a method with that signature
8Consuming Events (4) Handles Keyword
- Handles keyword connects events to the handler
method - Event must have the same signature as the handler
method - Handles has the following conventionltmethod
siggt Handles ltobjectgt.lteventgt
9Consuming Events (5) AddHandler and RemoveHandler
- First parameter is the event
- Second parameter is the AddressOf of the handler
- AddHandler
- Used to dynamically connect handlers to events
- Can be called multiple times for the same
event-handler combination - Handlers executed in the order that they were
added - RemoveHandler
- Used to dynamically remove handlers for events
- Must be called for each event-handler combination
that was added to fully disconnect an object
10Consuming Events (6) AddHandler and
RemoveHandler (continued)
- Events and garbage collection
- Handlers will keep objects alive
- A handled event is a pointer to a function in the
object handling the event - Event source keeps objects alive while it is
alive - Two Classes handle events from same object
- Both classes have a reference to event source
- Set class2 nothing without removing handlers
- class2 will not be garbage collected
- Event source has a pointer to functions in class2
- Remove handlers or destroy the event source
11Creating and Raising EventsPublic Event
Simplest Case
- Just declare the event with a signaturePublic
Event myEvent(ByVal str as String) - Exposes the event with the above signature
- Takes care of all the add and remove handlers
- Creates the delegates
- Also creates private delegate instance
12Creating and Raising Events (2) Creating
Delegates
- Delegates are outlines for function pointers
- Instances of delegates are function pointers
- Events are multicast delegates
- Delegate declarationPublic Delegate Sub
FileEvent(ByVal FullFileName As String) - Event declaration with delegatePublic Event
FileCompleted As FileEvent - Allows multiple events to be declared with the
same signature (delegate as template)
13Creating and Raising Events (3) Raise Event
- To raise an event, just use RaiseEventRaiseEven
t myEvent(strVal) - RaiseEvent method
- Checks to see if any handlers have been connected
to the delegate instance - Calls the private delegate instance
- The delegate instance then calls each handler
that has been added - In C you must do all this in code
14Creating and Raising Events (4) Convention for
Calling Events
- It is a convention to create an ON method that is
called to actually raise the eventPrivate Sub
OnMyEvent(strVal as String) RaiseEvent
myEvent(strVal)End Sub - Allows custom code before or after the event is
raised each time - ON method is called anytime that the event occurs
in code
15Creating and Raising Events (5) Functionality
Added by Compiler
- Event and delegate
- Event that does not use a delegate (simple
instance) will have a delegate created by the
compiler - Add and remove handler
- Methods that are called when a handler is added
or removed from an event are also created - Private delegate instance
- Private instance actually holds the function
pointers that are added to the public events and
are called to raise the event
16Review of Events from ILDASM Overview
17Review of Events from ILDASM (2) Delegate
Definitions
- The delegate definitions that are used by our
events - Multicast delegates
- Types of delegate instance that hold the function
pointers to the event handlers - DirectoryCompletedEventHandler was created by the
compiler
18Review of Events from ILDASM (3) Delegate
Definitions (continued)
Public Event DirectoryCompleted(ByVal
directoryName As String) Public Event
DirectoryStarted(ByVal directoryName As
String) Public Delegate Sub FileEvent(ByVal
FullFileName As String) Public Delegate Sub
FileFoundDelegate(ByVal FullFileName As String,
ByRef continue As Boolean)
19Review of Events from ILDASM (4) Public Events
- Public definitions of events that will be exposed
- Instances of delegate definitions
- Shell delegates do not actually hold any
references to handler methods - Contain an add/remove method for connecting
different handlers to these public events
20Review of Events from ILDASM (5) Public Events
(continued)
Public Event DirectoryCompleted(ByVal
directoryName As String) Public Event
DirectoryStarted(ByVal directoryName As
String) Public Event FileCompleted As
FileEvent Public Event FileFound As
FileFoundDelegate Public Event IterationStarted
As EventHandler
21Review of Events from ILDASM (6) Private
Delegate Instances
- Private definitions of the events that will be
exposed - Instances of the delegate definitions
- The add/remove methods of the public events add
and remove handlers to these multicast delegate
instances - Notice the word event is appended to the name of
each public event
22Review of Events from ILDASM (7) Add and Remove
Functions for Handlers
- Hidden add/remove events
- Called by runtime when adding and removing
handlers - Add function pointers to private delegate
instances - Created by the compiler
23Review of Events from ILDASM (8) Overview
24Advanced Event ConceptsThreads
- OLE/COM handled a lot of the marshalling of
events to the correct thread in legacy
architecture - Microsoft Visual Basic .NET is free threaded
- Events are raised on the currently executing
thread - No event queues except in the user interface
- Events are executed in a linear fashion unless
threading is explicitly used
25Advanced Event Concepts (2) User Interface
- UI updates must be carried out on the same thread
as the UI message pump (Win32 convention) - No guarantee that events will be raised on the
same thread if handled in a UI environment - UI can manage this using Invoke
- Can be dealt with in the event source
- Use a handle to a UI element and calling Invoke
- Setting up data return through polling
- WinForms timer
26Advanced Event Concepts (3) Invoke and
InvokeRequired
- Invoke
- Marshall a delegate instance back to a calling
thread - Uses the UI message pump of the control Invoke is
called on - InvokeRequired
- Tests if Invoke needs to be called based on the
current and UI thread context values
27Advanced Event Concepts (4) Invoke and
InvokeRequired (continued)
- Verify Invoke needs to be called
- If Label1.InvokeRequired Then
- Declare an array of event arguments
- Dim myArgs() As Object o, e
- Declare a delegate instance with the address of
the function to execute on the UI thread - Dim del As New Iterate_StartDelegate(AddressOf
Iterate_Start) - Call invoke on the control whose controlling
thread the delegate should be executed on - Label1.Invoke(del, myArgs)
28Advanced Event Concepts (5) Accessing Compiler
Created Variables
- Compiler creates many event components
- The event class can access these private events
but they do not show up in IntelliSense or the
Object BrowserIf Not IsNothing(FileFoundEvent)
Then FileFoundEvent(fileInfo.FullName,
con)End If - Accessing these private events allows an event
call similar to C
29Event ExamplePieces of the Event
- Class IterateFileSystem
- Declares the events
- Raises the events
- Main form
- Declares instance of IterateFileSystem
- Starts file system iteration on a new thread and
shows the Status form - Handles two IterateFileSystem events
- Status form
- Handles remaining IterateFileSystem Events
- Shows status of the file system iteration
30Event Example (2)Class IterateFileSystem
31Event Example (3) Class IterateFileSystem
- Raises initial events
- Exits when iteration is complete
32Event Example (4) Class IterateFileSystem
33Event Example (5) Main Form
- The text box takes a folder to be searched
- The Iteration Status label is changed when events
are raised from IterateFileSystem - Declares the initial instance of the event source
(IterateFileSystem) and status form - Passes reference to event source to status form
34Event Example (6)Main Form
35Event Example (7) Main Form
36Event Example (8) Main Form
37Event Example (9) Main Form
38Event Example (10) Status Form
- File event fires when a file is encountered and
updates main label and progress bar - Directory events update title bars and Cancel
button - Events are all connected with handles
- This form gets an instance of the event source
from the creating program
39Event Example (11) Status Form
40Event Example (12) Status Form
41Event Example (13) Status Form
- Must RemoveHandlers because the Event Source is
not destroyed - Handlers are pointers to the Form object and will
keep it alive - Removing handlers added with Handles keyword
42Summary
- Notification that something has occurred
- Event Source must create and raise events
- Consumer must create Event Source WithEvents
- Consumer must handle at least some events
43Additional Resources
- Q319823 HOW TO Handle Events in Visual Basic
.NET - MSDN Event Handlers Visual Basic and
Chttp//msdn.microsoft.com/library/default.asp?
url/library/en-us/vbcon/html/vboriEventHandlers.a
sp - MSDN Event Handling in Windows
Formshttp//msdn.microsoft.com/library/default.a
sp?url/library/en-us/vbcon/html/vbconEventHandlin
g.asp
44- Thank you for joining todays Microsoft Support
- WebCast.
- For information about all upcoming Support
WebCasts, - and access to the archived content (streaming
media - files, PowerPoint slides, and transcripts),
visit - http//support.microsoft.com/webcasts/
- Your feedback is sincerely appreciated. Please
send any - comments or suggestions about the Support
- WebCasts to supweb_at_microsoft.com.