Search code examples
delphiinheritancekeypress

Delphi how to implement baseclass event?


I have an abstract Delphi XE form that acts as base class for a family of forms used in my application. I am trying to figure out the best way to make a help function (on F1 keypress) that opens a wiki-page for the active form.

I'd very much like this function to be implemented at base-class level and to call when the user presses F1 but I need some advice on how to do this in a smart way. Currently I just put a KeyDown-event on the base form but this gets overwritten if the subform receives its own KeyDown, at which point I have to manually call the baseKeyDown. Obviously, this is not optimal.. Is there a way to ensure I catch the F1 keypress at baseclass level, random overloads nonwithstanding?

I am running Delphi XE on Windows 7


Solution

  • You should override KeyDown method in your base form class.

    type
      TBaseForm = class(TForm)
      protected
        procedure KeyDown(var Key: Word; Shift: TShiftState); override;
      end;
    
    procedure TBaseForm.KeyDown(var Key: Word; Shift: TShiftState);
    begin
      // do your processing here
      // ...
      inherited; // call inherited method that will call OnKeyDown if assigned
    end;
    

    This is default implementation of KewDown method that calls OnKeyDown events

    procedure TWinControl.KeyDown(var Key: Word; Shift: TShiftState);
    begin
      if Assigned(FOnKeyDown) then FOnKeyDown(Self, Key, Shift);
    end;