AddHandler
From Real Software Documentation
Used to delegate the responsibility of handling an event to a method.
Notes
The event can be any event, not just control events, and the method can be any method that is in scope.
Syntax
AddHandler <event>, <delegate method>
| Part | Description |
|---|---|
| event | The event you want a method to handle. |
| delegate method | The method you wish to handle the event. |
What for ?
You may want to have a Timer or a Thread in a custom class that can be instantiated via code. Usually, you would need to create a subclass of Timer or Thread whose main event, Action or Run event, contains the code you want to be executed. However, you may want to create an all-in-one class. In that case, you can instantiate the Timer or the Thread and delegate their main event to a method contained in your custom class using AddHandler.
Notes
The delegate method declaration must be composed of:
- A reference to the object (the sender object) whose event is to be handled. It must be the first parameter and the type must match the object’s class or its super class.
- The same parameters of the event in exactly the same order and with the same types (parameters’ names can be changed though).
- If the event returns a value, the delegate method must return the same value type.
A handler can handle any number of events, but an event can only have one event handler. To change the event handler for an event (after you have added one), you must first remove the existing handler using RemoveHandler and then add the new one. If you don’t, a RuntimeException will be raised.
Example
This example specifies a method called “MyTimeOut” as the handler of the Action event of a Timer, myTimer, that was instantiated in code:
Because the Action event of a Timer takes no parameters and does not return a value, the “MyTimeOut” method must be declared as:
As stated in the Notes, the sender can be a super class as well. For example, the following delegate method would also work for a Canvas because Canvas is a RectControl and it implements a MouseDown event:
// so the delegate method must include the same parameters and return the same value type
Function myDelegateMethod( sender As RectControl, x As Integer, y As Integer ) As Boolean
In this example, there is a PushButton in Window1 with the following Action event:
The code calls the Window method myhandler that consists of the following code:
System.DebugLog(CurrentMethodName + " start doing stuff ")
Dim tck As Integer = ticks + 300
While ticks < tck
System.DebugLog(CurrentMethodName + " doing stuff ")
Wend
System.DebugLog(CurrentMethodName + " end doing stuff ")
End Sub
It writes to the log as the While loop is executing. On the Mac, the log is seen in the Console application. As it is running, the log looks like this:
See Also
RemoveHandler statement
