Delphi coding hints and tips.

Using return key instead of tab.

To use the return key to move to the next control instead of the tab key attach the following code to the controls OnKeyPress event handler: -

procedure TForm1.Edit1KeyPress(Sender: TObject; 
var Key: Char);
begin
if Key=Chr(VK_RETURN)
then
  begin
  {kill return key press so get no error beep!}
  Key:=#0;
  {now post windows message for tab key press.}
  PostMessage(Self.Handle,WM_KEYDOWN,VK_TAB,0);
  end;
end;

The above OnKeyPress event handler is for a simple Tedit. It works by detecting when the return key is pressed and then substituting a tab key press in it place. You have to create a WM_KEYDOWN message rather than just setting the Key:=Chr(VK_TAB). This is because the OnKeyPress event handler in controls does not handle VK_TAB press. Try trapping for VK_TAB in an OnKeyPress event handler and pressing the tab key, OnKeyPress does not get called.

If you have several controls, which require the return key to tab, you could use the same event handler for all there OnKeyPress. Just point all there OnKeyPress's at the same procedure.

You could also put the above code into a TForms OnKeyPress and set the forms KeyPreview property to true. This would have a global effect such that all controls would 'try' to tab when you hit return without having to code there individual OnKeyPress's. I say 'try' because pressing the return key when a button has focus will cause the button to click and not tab to the next control.

Note shift+return will go to the previous control just a shift+tab as the above trap just changes return to tab leaving shift pressed.