Delphi event handling, how to create own event

后端 未结 4 1073
孤独总比滥情好
孤独总比滥情好 2020-12-02 11:08

I am new to delphi development. I have to create an event and pass some properties as parameters. Could someone share some demo program that shows how to do this from scratc

4条回答
  •  长情又很酷
    2020-12-02 11:18

    The complete project answer is good. But this is an alternate answer showing how to do what you want, in a form you already have.

    Go into your form, and go to the interface section, in the types area, outside your form's class definition and add a type:

     interface
     type
      TMyEvent = procedure(Sender:TObject;Param1,Param2,Param3:Integer) of object;
    
      TMyForm = class(TForm)
                ....
    

    It is traditional, but not required, that the first item in your event be the object sending it, but to use base class TObject instead of your form's actual class type.
    The other parameters above are not required at all, but are showing you how you would declare your own additional data. if you don't need them, then just use Sender:TObject. And in that case, you don't have to define TMyEvent at all, just use the TNotifyEvent type.

    Now declare a field that uses that type, in your form:

    TMyForm = class(TForm)
     private
       FMyEvent : TMyEvent;
      ...
    

    Now declare a property that accesses that field, in your form's properties section:

      // this goes inside the class definition just before the final closing end 
     property MyEvent:TMyEvent read FMyEvent write FMyEvent
    

    Now go to where you want that event to 'fire' (get called if it is set) and write this:

    // this goes inside a procedure or function, where you need to "fire" the event.
    procedure TMyForm.DoSomething;
    begin
      ...
      if Assigned(FMyEvent) then FMyEvent(Self,Param1,Param2,Param3);
    end;
    

提交回复
热议问题