Delphi event handling, how to create own event

后端 未结 4 1065
孤独总比滥情好
孤独总比滥情好 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:26

    You use an event handler to react when something else happens (for example AfterCreation and before closing).

    In order to use events for your own class, you need to define the event type. Change the type and number of parameters needed.

    type
      TMyProcEvent = procedure(const AIdent: string; const AValue: Integer) of object;
      TMyFuncEvent = function(const ANumber: Integer): Integer of object;
    

    In the class, you can add a DoEvent (rename for the proper event). SO you can call the DoEvent internally. The DoEvent handles the possibility that an event is not assigned.

    type
      TMyClass = class
      private
        FMyProcEvent : TMyProcEvent;
        FMyFuncEvent : TMyFuncEvent;
      protected
        procedure DoMyProcEvent(const AIdent: string; const AValue: Integer);
        function DoMyFuncEvent(const ANumber: Integer): Integer;
    
      public
        property MyProcEvent: TMyProcEvent read FMyProcEvent write FMyProcEvent;
        property MyFuncEvent: TMyFuncEvent read FMyFuncEvent write FMyFuncEvent;
      end;
    
    procedure TMyClass.DoMyProcEvent(const AIdent: string; const AValue: Integer);
    begin
      if Assigned(FMyProcEvent) then
        FMyProcEvent(AIdent, AValue);
      // Possibly add more general or default code.
    end;
    
    
    function TMyClass.DoMyFuncEvent(const ANumber: Integer): Integer;
    begin
      if Assigned(FMyFuncEvent) then
        Result := FMyFuncEvent(ANumber)
      else
        Result := cNotAssignedValue;
    end;
    

提交回复
热议问题