Event Handlers Have A Return Type of void (C++)

From RAD Studio
Jump to: navigation, search

Go Up to Defining the Handler Type


Event handlers must have a return type of void. Even though the handler can return only void, you can still get information back from the code of the user by passing arguments by reference. When you do this, make sure you assign a valid value to the argument before calling the handler so you do not require the user's code to change the value.

An example of passing arguments by reference to an event handler is the key-pressed event, of type TKeyPressEvent. TKeyPressEvent defines two arguments: one to indicate which object generated the event, and one to indicate which key was pressed:

typedef void __fastcall (__closure *TKeyPressEvent)(TObject *Sender, Char &Key);

Normally, the Key parameter contains the character pressed by the user. Under certain circumstances, however, the user of the component might want to change the character. One example might be to force all characters to uppercase in an edit control. In that case, the user could define the following handler for keystrokes:

void __fastcall TForm1::Edit1KeyPress(TObject *Sender, Char &Key)
{
  Key = UpCase(Key);
}

You can also use arguments passed by reference to let the user override the default handling.

See Also