Definition of Events in Visual Basic

By Mark Keller

In Microsoft Visual Basic, an event is a message sent by an object within a program to the main program loop, informing it that something has happened. This "something" can vary widely, from a timer running out to a mouse-click on the part of the user. The program can capture this event and use the information within it to make decisions about further operations.

Examples

Visual Basic comes preloaded with a vast quantity of precoded events, though users can also write their own. These events cover nearly every aspect of program operation and interaction. Some events related to the interaction between the mouse cursor and a control on a Form (such as a button) include MouseClick, MouseDoubleClick, MouseEnter, MouseLeave, MouseWheel, MouseMove and MouseHover. Events are generally given very intuitive names, to make reading the Visual Basic code easier.

Triggering

Events can be triggered by a wide number of situations. Many events are the result of user interaction, such as mouse movement or keyboard entry. The Windows operating system also sends events, notifying the program of when it is minimized or when another window overlaps it. Objects can set off their own events, when a variable has reached a certain value, for instance. Finally, events can be set in motion by specifically programming them to do so, by means of what is called "raising."

Declaration

New events are created by using a declaration command. The code for this generally looks something like what follows:Public Event OptionChanged(ByVal Name As String, ByVal Number As Integer)This example event would have to be manually programmed to be raised upon the changing of an option, and would send two values to the program: the name of the option changed and the value to which it was set.

Raising Events

Raising an event is the act of causing it to happen. This can be done with a single line of code placed in your program, such as:RaiseEvent OptionChanged("Length", 28)This will then notify the program of the event's taking place, and will send the information contained to a handler procedure, if one exists.

Handlers

A handler is a procedure that the program calls when a specific event takes place. The handler can then react to the information, processing it or sending information to the user. First the event and its handler must be associated by hand, so the program knows that the one should call the other. For example, to add a handler to our OptionChanged event, something like this is required:AddHandler Obj.OptionChanged, AddressOf Me.OptionChangedHandlerAfter which the handler itself can be added. A handler for OptionChanged might be as follows:Sub OptionChangedHandler(ByVal Name As String, ByVal Number As Integer) MsgBox("The value for " & Name.ToString & "has been changed!)End Sub