Mirror

How to make the [Enter] key behave like the [Tab] key (Views: 100)


Problem/Question/Abstract:

How to make the [Enter] key behave like the [Tab] key

Answer:

Solve 1:

You need to trap the keystroke and set up your own response to it. Try this: (Note: This will not work within a DBGrid, since the next field is not a separate object.)

procedure TMainForm.FormCreate(Sender: TObject);
begin
  keyPreview := true; {To turn the event "ON"}
end;

procedure TMainForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
  begin
    Key := #0;
    PostMessage(Handle, WM_NEXTDLGCTL, 0, 0);
  end;
end;


Solve 2:

Use this code for example for an TEdit's OnKeyPress event:

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
  begin
    SelectNext(Sender as TWinControl, True, True);
    Key := #0;
  end;
end;

This causes Enter to behave like tab. Now, select all controls on the form you'd like to exhibit this behavior (not Buttons) and go to the Object Inspector and set their OnKeyPress handler to EditKeyPress. Now, each control you selected will process Enter as Tab. If you'd like to handle this at the form (as opposed to control) level, reset all the controls OnKeyPress properties to blank, and set the form's OnKeyPress property to EditKeyPress. Then, change Sender to ActiveControl and set the form's KeyPreview property to true:

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
  begin
    SelectNext(ActiveControl as tWinControl, True, True);
    Key := #0;
  end;
end;

This will cause each control on the form (that can) to process Enter as Tab.


Solve 3:

Handle this in the OnKeyPress event. The form's KeyPreview property must be set to true.

procedure TFrmEnterTab.FormKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = Chr(VK_RETURN) then
  begin
    if GetKeyState(VK_SHIFT) < 0 then
      SelectNext(ActiveControl, false, true)
    else
      SelectNext(ActiveControl, true, true);
    Key := #0;
  end;
end;

<< Back to main page