Write Components which handle ENTER-Key like TAB-Key (Views: 101)


Standard-behaviour of controls when pressing ENTER-KEY is a BEEP-Sound. But how to write Components which handle ENTER-Key like TAB-Key?


This Article will show how to write Components which will handle the ENTER-Key in the same behaviour like the TAB-Key. As Sample I will take a TEdit-Component but it should work on oll other components with OnKeyPress-Event.

Create a new Component from TEdit with a new property:

EnterNextCtrl: Boolean

If this is TRUE (standard), the Focus will jump to next Control if the user press ENTER. If it is FALSE it will show standard-behaviour (beep). This functionality is included in OnKeyPress-Event. There the component sends the Message "WM_NextDLGCTL" to the parent Form. It's important to get the ParentForm, because the TMyEdit need not included on TForm directly but maybe on a TPanel. So you have to send the message directly to the parent-FORM (and not to PARENT, which may be a TPanel).

It should be possible to use this way for other components which have a OnKeyPress-Event.

  TMyEdit = class(TEdit)
    FEnterNextCtrl: Boolean;
    procedure KeyPress(var Key: Char); override;
    property EnterNextCtrl: Boolean read FEnterNextCtrl write FEnterNextCtrl;
    constructor Create(AOwner: TComponent); override;

constructor TMyEdit.Create(AOwner: TComponent);
  FEnterNextCtrl := TRUE;

procedure TMyEdit.KeyPress(var Key: Char);
  ParentForm: TCustomForm;
  if key = #13 then
    Key := #0;

    //Get the parent-Form.
    ParentForm := GetParentForm(self);

    if FEnterNextCtrl = TRUE {//Jump to next Control or beep } then
      parentform.Perform(WM_NextDLGCTL, 0, 0)

<< Back to main page