Author: Jonas Bilinkevicius
Using Delphi 5, I'm trying to setup a routine that would automatically turn off the
NUMLOCK key when loaded. Assume that I am writing a standalone utility that could
be loaded in the startup folder to do this function.
Answer:
Solve 1:
1
2 procedure SwitchToggleKey(Key: byte; State: boolean);
3 var
4 ks: TKeyboardState;
5 ScanCode: integer;
6 begin
7 if not key in [VK_CAPITAL, VK_NUMLOCK, VK_SCROLL, VK_INSERT] then
8 exit;
9 if (key = VK_NUMLOCK) and (Win32Platform = VER_PLATFORM_WIN32_WINDOWS) then
10 begin
11 GetKeyboardState(ks); {for Win95/98}
12 if state then
13 ks[key] := ks[key] or 1
14 else
15 ks[key] := ks[key] and 254;
16 SetKeyboardState(ks);
17 end
18 else if odd(GetKeyState(key)) <> state then
19 begin
20 ScanCode := MapVirtualKey(key, 0);
21 keybd_event(key, ScanCode, {KEYEVENTF_EXTENDEDKEY} 0, 0);
22 {Simulate a key release}
23 keybd_event(key, ScanCode, {KEYEVENTF_EXTENDEDKEY or } KEYEVENTF_KEYUP, 0);
24 end;
25 end;
Note that not all controls "honor" the INSERT key, and others will only respond to
the INSERT key while they have focus. I'm surprised that the Extended Key
"attribute" works for the non-extended keys. Strangely enough, it works as well
without KEYEVENTF_EXTENDEDKEY.
Solve 2:
26
27 procedure SimulateKeystroke(Key: byte; extra: DWORD);
28 begin
29 keybd_event(Key, extra, 0, 0);
30 keybd_event(Key, extra, KEYEVENTF_KEYUP, 0);
31 end;
32
33 function IsKeyToggled(key: byte): boolean;
34 var
35 state: word;
36 begin
37 state := windows.GetKeyState(key);
38 result := (state mod 128) = 1;
39 end;
40
41 function CapsLockStatus: boolean;
42 begin
43 result := IsKeyToggled(VK_CAPITAL);
44 end;
45
46 function NumLockStatus: boolean;
47 begin
48 result := IsKeyToggled(VK_NUMLOCK);
49 end;
50
51 procedure ToggleCapsLock;
52 begin
53 SimulateKeystroke(VK_CAPITAL, 0);
54 end;
55
56 procedure ToggleNumLock;
57 begin
58 SimulateKeystroke(VK_NUMLOCK, 0);
59 end;
60
61 procedure TForm1.btnOnClick(Sender: TObject);
62 begin
63 if not NumLockStatus then
64 ToggleNumLock;
65 end;
66
67 procedure TForm1.btnOffClick(Sender: TObject);
68 begin
69 if NumLockStatus then
70 ToggleNumLock;
71 end;
Solve 3:
I want to determine the state of the Num lock key on the keyboard and set it to on
when my application begins or opens a specific form.
Note that the keyboard LED may not reflect the keys state correctly on all Windows
platforms if you set it this way in code.
72
73 procedure SetLockKey(vcode: Integer; down: Boolean);
74 begin
75 if Odd(GetAsyncKeyState(vcode)) <> down then
76 begin
77 keybd_event(vcode, MapVirtualkey(vcode, 0), KEYEVENTF_EXTENDEDKEY, 0);
78 keybd_event(vcode, MapVirtualkey(vcode, 0), KEYEVENTF_EXTENDEDKEY or
79 KEYEVENTF_KEYUP, 0);
80 end;
81 end;
82
83 SetLockKey(VK_NUMLOCK, True); {num lock down}
|