Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do events in Delphi work?

Tags:

events

delphi

I'm trying to get console output from a program using this library uZpRunConsoleApp. It's well documented but I've not used Delphi for very long and I don't understand how events work.

From what I can tell I need to call ExecuteConsoleApp with my application, which I have working with no output. It looks like that method wants me to specify a function it can fire when an event happens but I don't understand how to do that.

I hope somebody can spread some light here.

I didn't post any code since this isn't really a code specific problem, but if somebody wants what I have so far I'll edit for them.

like image 384
Nowayz Avatar asked Aug 02 '10 02:08

Nowayz


1 Answers

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

The event type is defined like this:

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

What that means is that it's a reference to an object 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 of object bit is important. This is specifically a method reference and not a reference to a standalone function.

What the event handler is for is to allow you to customize the way ExecuteConsoleApp works. It's almost exactly like adding code to a button in the Form Designer. You place the button on the form, then you assign an event handler to its OnClick event that customizes the button by adding in code that executes when the button is clicked. The difference is that here, you don't have a Form Designer to wire it together for you.

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

like image 146
Mason Wheeler Avatar answered Nov 12 '22 12:11

Mason Wheeler