How to Focus the Next Control After Pressing Enter
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);
Excellent, thanks!
I have a number of data-aware lookup-controls, edits, comboboxes, memos… They all work with the same event handler + code.
Note that the Perform is a function of the FORM where the event handler is. Trying (Sender as TControl).Perfrom will do nothing visible. If you want to have this code as a function in arbitrary unit, you will need to find out the parent of the “Sender” first. You could start by trying:
if (Sender as TControl).HasParent then
xxx := (Sender as TWinControl).GetParentComponent;
WARNING: I haven’t tried this yet, but I have a feeling that component is not the correct way to go… could be, could be not.