Archive

Posts Tagged ‘working’

How to Focus the Next Control After Pressing Enter

December 15th, 1999 m3Rlin 1 comment

By default the focus is passed to the next control by pressing the Tab key. Well, sometimes (when filling out forms) you may want to pass to the next control after pressing Enter. Well, here’s the code: For TEdit controls only:
Select all the TEdit controls you want to include (using the Shift key), then select the Object Inspector, choose the Events tab and double click the OnKeyPress event. This way all the selected TEdit controls will use the same code. In the code editor write this code:

if Key = #13 then begin
  Perform(WM_NEXTDLGCTL, 0, 0);
  Key := #0; { Eat the key }
end;

For all the controls on the form:
This method will work for all controls because the form will take care of the event. All you have to do is set the form’s KeyPreview property to True and add this code to your form’s KeyUp event:

if (Key = VK_RETURN) and (Shift = []) then
  Perform(WM_NEXTDLGCTL, 0, 0);

How to Focus the Next Edit Control With the Enter Key II

December 15th, 1999 m3Rlin 1 comment

When creating forms with a lot of data entry you may want to consider the option to let the user focus the next edit control by hitting the Enter key. The default key is Tab which can become annoying :-)
All we have to do is add the following code the each TEdit control on the form. You can do so by holding down the shift key and selecting each control. Then click the ObjectInspector and double click on OnKeyPress to create a shared event for all the controls. Then enter this code in the event procedure:

  ...
  uses
    Windows;
  ...
  if Key = #13 then begin
    { Make Windows focus the next edit control }
    Perform(WM_NEXTDLGCLTL, 0, 0);
    { Eat the enter key }
    Key := #0;
  end;
  ...

This code will work only with the controls that use this OnKeyPress event.
If you want all the edit controls on the form to act this way use a different way. This code does not require each edit control to use the above routine. Just the form’s KeyPreview property to True. Now add this code to the form’s KeyUp event and your all set :-) If, for some reason you want to exclude any edit control from using Enter key instead to pass the focus all you have to do is modify the if condition to exclude certain edits. Instead of using there names you may want to consider the Tag property for this.

  ...
  if (Key = VK_RETURN) and ([ssCtrl, ssShift] * Shift = []) then
    Perform(WM_NEXTDLGCTL, 0, 0);
  ...

Note: Tip #42 refers to this topic too.