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

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.

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

No Comments Yet

You can be the first to comment!

Leave a comment

OpenID Login

Standard Login