How do events work in Delphi?

I am trying to get console output from a program using this library uZpRunConsoleApp . This is well documented, but I haven't used Delphi for a very long time, and I don't understand how events work.

From what I can say, I need to call ExecuteConsoleApp with my application, which runs without output for me. It looks like this method wants me to specify a function that it can run when an event occurs, but I don't understand how to do it.

I hope someone can spread a little light here.

I did not publish the code, since it is not a problem related to the code, but if someone wants what I have so far, I will edit for them.

+6
events delphi
source share
1 answer

Yes, an event handler is basically a function reference. If you've ever used callbacks, this is basically the same idea. If not, here is a quick overview:

The type of event is defined as follows:

TZpOnNewTextEvent = procedure(const Sender: TObject; const aText: string) of object; 

This means that this is a reference to a method of object with a signature that looks like this:

 type TMyObject = class (TMyObjectAncestor) //stuff here procedure MyEventHandler(const Sender: TObject; const aText: string); //more stuff here end; 

The bit of object important. This, in particular, is a reference to a method, and not a reference to an autonomous function.

For an event handler, you can configure the ExecuteConsoleApp method. This is almost the same as adding code to a button in the form designer. You put the button on the form, and then you assign the OnClick event handler, which sets up the button, adding the code that executes when the button is clicked. The difference is that here you do not have a form constructor to link it for you.

Fortunately, the syntax is pretty simple. For procedure (whatever) of object you pass an event handler just by specifying a name. Throw Self.MyEventHandler in the right place in the parameter list, and it will work.

+12
source share

All Articles