Although the compiler allows you to declare method-pointer types that are functions, you should never do so for handling events. Because an empty function returns an undefined result, an empty event handler that was a function might not always be valid. For this reason, all your events and their associated event handlers should be procedures.
Although an event handler cannot be a function, you can still get information from the application developer's code using var parameters. When doing this, make sure you assign a valid value to the parameter before calling the handler so you don't require the user's code to change the value.
An example of passing var parameters to an event handler is the OnKeyPress event, of type TKeyPressEvent. TKeyPressEvent defines two parameters, one to indicate which object generated the event, and one to indicate which key was pressed:
type TKeyPressEvent = procedure(Sender: TObject; var Key: Char) of object;
Normally, the Key parameter contains the character pressed by the user. Under certain circumstances, however, the user of the component may want to change the character. One example might be to force all characters to uppercase in an editor. In that case, the user could define the following handler for keystrokes:
procedure TForm1.Edit1KeyPressed(Sender: TObject; var Key: Char); begin Key := UpCase(Key); end;
You can also use var parameters to let the user override the default handling.
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!