Author: Tomas Rutkauskas
I have 4 buttons on a form, let's say button1 and button2 on the left side on the
form and button3 and button4 on the right side on the form. When Button1 has the
focus and I press the RightArrow I want to have Button3 to get the focus instead of
Button2. When Button3 has the focus and I press the LeftArrow I want to have
Button1 to get the focus. I've tried the onkeydown event on the button but it
ignores to trap the arrowkeys.
Answer:
Buttons do not process navigation keys, so they go to the form in the guise of
CM_DIALOGKEY messages and the form processes them to move to the next/ previous
control in tab order. You may be able to achieve what you want by simply changing
the tab order of your buttons (assuming they are all sitting on the same parent
control).
To handle this all yourself you would add a handler for the CM_DIALOGKEY message to
the form.
1 {form private section}2 3 procedure CMDialogKey(var msg: TCMDialogKey); message CM_DIALOGKEY;
4 5 procedure TForm1.CMDialogKey(var msg: TCMDialogKey);
6 begin7 case Msg.Charcode of8 VK_RIGHT:
9 begin10 if ActiveControl = Button1 then11 begin12 Button3.Setfocus;
13 msg.result := 1; {mark key handled}14 Exit;
15 end;
16 if ActiveControl = Button2 then17 begin18 Button4.Setfocus;
19 msg.result := 1; {mark key handled}20 Exit;
21 end;
22 end;
23 VK_LEFT:
24 begin25 if ActiveControl = Button3 then26 begin27 Button1.Setfocus;
28 msg.result := 1;
29 Exit;
30 end;
31 if ActiveControl = Button4 then32 begin33 Button2.Setfocus;
34 msg.result := 1;
35 Exit;
36 end;
37 end;
38 end;
39 inherited;
40 end;
41 end;