Make The Enter Key Work Like Tab

Focus Next Entry Control On Enter Key Press

Close-up Of Enter Key On Laptop
Getty Images/Prateek Prajapati/EyeEm

We know that, generally, pressing the Tab key moves the input focus to next control and Shift-Tab to previous in the tab order of the form. When working with Windows applications, some users intuitively expect the Enter key to behave like a Tab key.

There is a lot of third-party code for implementing better data entry processing in Delphi. Here are a few of the best methods out there (with some modifications).

Examples below are written with the assumption that there is no default button on the form. When your form contains a button whose Default property is set to True, pressing Enter at runtime executes any code contained in the button's OnClick event handler.

Enter as Tab

The next code causes Enter to behave like Tab, and Shift+Enter like Shift+Tab:

~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TForm1.Edit1KeyPress (Sender: TObject; var Key: Char) ;
begin
   If Key = #13 Then Begin
    If HiWord(GetKeyState(VK_SHIFT)) <> 0 then
     SelectNext(Sender as TWinControl,False,True)
    else
     SelectNext(Sender as TWinControl,True,True) ;
     Key := #0
   end;
end;

~~~~~~~~~~~~~~~~~~~~~~~~~

in DBGrid

If you want to have similar Enter (Shift+Enter) processing in DBGrid:

~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TForm1.DBGrid1KeyPress (Sender: TObject; var Key: Char) ;
begin
   If Key = #13 Then Begin
    If HiWord(GetKeyState(VK_SHIFT)) <> 0 then begin
     with (Sender as TDBGrid) do
     if selectedindex > 0 then
      selectedindex := selectedindex - 1
     else begin
      DataSource.DataSet.Prior;
      selectedindex := fieldcount - 1;
     end;
    end else begin
     with (Sender as TDBGrid) do
     if selectedindex < (fieldcount - 1) then
      selectedindex := selectedindex + 1
     else begin
      DataSource.DataSet.Next;
      selectedindex := 0;
     end;
   end;
   Key := #0
   end;
end;

~~~~~~~~~~~~~~~~~~~~~~~~~

More Info on Delphi Applications

  • Keyboard Symphony Get familiar with the OnKeyDown, OnKeyUp, and onKeyPress event procedures to respond to various key actions or handle and process ASCII characters along with other special purpose keys.
  • What Does #13#10 Stand for, in Delphi Code? If you are wondering what those characters stand for, here's the answer.
Format
mla apa chicago
Your Citation
Gajic, Zarko. "Make The Enter Key Work Like Tab." ThoughtCo, Feb. 16, 2021, thoughtco.com/make-the-enter-key-work-like-tab-1058389. Gajic, Zarko. (2021, February 16). Make The Enter Key Work Like Tab. Retrieved from https://www.thoughtco.com/make-the-enter-key-work-like-tab-1058389 Gajic, Zarko. "Make The Enter Key Work Like Tab." ThoughtCo. https://www.thoughtco.com/make-the-enter-key-work-like-tab-1058389 (accessed March 28, 2024).