Author: Jonas Bilinkevicius
How to make the [Enter] key behave like the [Tab] key
Answer:
Solve 1:
You need to trap the keystroke and set up your own response to it. Try this: (Note:
This will not work within a DBGrid, since the next field is not a separate object.)
1 procedure TMainForm.FormCreate(Sender: TObject);
2 begin
3 keyPreview := true; {To turn the event "ON"}
4 end;
5
6 procedure TMainForm.FormKeyPress(Sender: TObject; var Key: Char);
7 begin
8 if Key = #13 then
9 begin
10 Key := #0;
11 PostMessage(Handle, WM_NEXTDLGCTL, 0, 0);
12 end;
13 end;
Solve 2:
Use this code for example for an TEdit's OnKeyPress event:
14
15 procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
16 begin
17 if Key = #13 then
18 begin
19 SelectNext(Sender as TWinControl, True, True);
20 Key := #0;
21 end;
22 end;
This causes Enter to behave like tab. Now, select all controls on the form you'd
like to exhibit this behavior (not Buttons) and go to the Object Inspector and set
their OnKeyPress handler to EditKeyPress. Now, each control you selected will
process Enter as Tab. If you'd like to handle this at the form (as opposed to
control) level, reset all the controls OnKeyPress properties to blank, and set the
form's OnKeyPress property to EditKeyPress. Then, change Sender to ActiveControl
and set the form's KeyPreview property to true:
23
24 procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
25 begin
26 if Key = #13 then
27 begin
28 SelectNext(ActiveControl as tWinControl, True, True);
29 Key := #0;
30 end;
31 end;
This will cause each control on the form (that can) to process Enter as Tab.
Solve 3:
Handle this in the OnKeyPress event. The form's KeyPreview property must be set to
true.
32 procedure TFrmEnterTab.FormKeyPress(Sender: TObject; var Key: Char);
33 begin
34 if Key = Chr(VK_RETURN) then
35 begin
36 if GetKeyState(VK_SHIFT) < 0 then
37 SelectNext(ActiveControl, false, true)
38 else
39 SelectNext(ActiveControl, true, true);
40 Key := #0;
41 end;
42 end;
|