Home Articles Books Downloads FAQs Tips

Q: Assign event handlers at runtime?

Step 1: Identify out what type of handler you will be writing. OnClick event handlers are TNotifyEvent types. The OnIdle event of TApplication is of the type TIdleEvent, and it passes two arguments to its handler. The VCL help file can help you identify what type of handler you should create for a particular event. For OnIdle, the help file lists:

__property TIdleEvent OnIdle;

Step 2: Determine what type of variable the function should return (almost always void), and what variables should be passed to the function. Unfortunately, the help file leaves this part out. For events that could have been created at design time (such as OnClick), you could create a dummy handler, and then cut and paste the function declarations. For handlers that cannot be created at design time, you must refer to the include files.

The TApplication handler types are listed in FORMS.HPP. You might want to open the file now and take a look. Find the typedef for TIdleEvent. It should look something like:

typedef void __fastcall (__closure *TIdleEvent)(System::TObject* Sender,
                                                bool &Done);

This means that an OnIdle function should look like this:

void __fastcall TForm1::AppIdle(System::TObject *Sender, bool &Done)

Step 3: Add the function declaration to the class that is handling the event. For OnIdle it would look like this:

class TForm1 : public TForm
{
    __published:
    private:
        void __fastcall AppIdle(System::TObject *Sender, bool &Done);


Step 4: Code the function body.

void __fastcall TForm1::AppIdle(System::TObject *Sender, bool &Done)
{
    // function body here
}

Step 5: And now, the step you have all been waiting for. To associate your handler function to a component's event, you must assign the function name to the handler. The most convenient place to do this is inside the constructor of the class that contains the handler function.

__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
    Application->OnIdle = AppIdle;
}

Notice that there is nothing fancy here. Just assign the function name to the handler. Do not assign the address of the function to the handler.



Copyright © 1997-2000 by Harold Howe.
All rights reserved.