简体   繁体   中英

How do events in Delphi work?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM