Re: Delphi text box (TEdit) and keypress

Posted by webmaster Guido

In Reply to: New User. Help with text boxes.

: I've tried JAva and VB and moved on to Delphi. So, I have two text boxes and want the user to press the 'enter' key to move from one box to the other. How? Do I have to make it like a tab key? I will also want the enter key to execute a button as well at the end of the form.

To find out which key is pressed in a TEdit (edit-box), you've got to write a handler for its OnKeyPress event. An example:

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
  if Key = #13 then begin
    SelectNext(Sender as tWinControl, True, True );
    if Sender = Edit10 then
      Button1.Click; // let the button click itself
    Key := #0;

When key #13 is pressed (Enter), SelectNext moves the input focus from the current control (in this case Edit1) to the next one. That is, if there is a "next" control in the same "container": if all your TEdits are directly put on Form1, than the "container" is Form1, so in this case Edit2 receives the focus (see note at end of message for other containers).

Important for this to work properly is the "tab order" of the controls. Let's say that we have 4 TEdits and a button, then the tab order should be: Edit1 - Edit2 - Edit3 - Edit 4 - Button1.

Here's a slightly reworded text from Delphi's help:

procedure SelectNext(CurControl: TWinControl; GoForward, CheckTabStop: Boolean);

SelectNext finds the next child control in the control?s tab order. If SelectNext can't find a "next" control (as defined by its parameters), the focus remains with the current Control.

CurControl: current control, from which to begin the search.
GoForward: direction of the search. If GoForward is True, FindNextControl searches forward through the child controls. If GoForward is False, FindNextControl searches backward.
CheckTabStop: must the control that SelectNext finds have its TabStop property set to True? If CheckTabStop is True and the next control does not have TabStop = True, then the search for the next control continues.

Note: if the controls (TEdits, Tbuttons,...) are placed on a TPanel, that panel is the container, the "parent". Then, Panel1.SelectNext moves to the next control that is on the panel.
In that case, you must write Panel1.SelectNext instead of simply SelectNext. Writing SelectNext without a prefix means in fact Form1.SelectNext, because that is implied automatically because the procedure TForm1.Edit1KeyPress is a "method of Form1".

Don't be frustrated if you don't get this last remark, that's Delphi's OOP (object oriented programming) at work ;-)
Explaining OOP would take a complete book instead of a simple message on DelphiLand's forum...