In this short tutorial, C++ Product Manager, David Millington, explains what event handlers are and how to use them in your C++ application development.
- The event is that something happens, such as a button being clicked
- Event handler – a method that’s called when something happens so your code can respond to it
- Technical details: an object-method pointer, referring to both the method and object instance on which to call the method. And it can have any signature.
- Usually named On-something, such as OnPaint. The method assigned to a control’s OnPaint property will be called by that control when it paints.
Defining Event Handlers
In an event receiver class, such as your form, you define event handlers, which are simply methods that match the event handler type (return type, calling convention, and arguments) that match the event that they will handle. They are assignable like method pointers (since they are an object-oriented method pointer) to variables. Usually you do this in the Object Inspector, since events are heavily used for UI code: you will create an event handler (method) for (say) an OnClick event from the IDE, which will generate an empty method for you you can use to fill in the behaviour you want.
Code that handles events, ie sees something happen, just calls that method pointer to invoke your method.
To fire an event, simply check if the method pointer is null or not, and if not, call it. Usually you don’t need to worry about this: you define the methods and assign them, and existing library code, like a button class, looks after calling them.
Be sure to check out other tutorials on C++ Builder here: