Recent

Author Topic: Cross-platform way to get and toggle the Num Lock state  (Read 522 times)

jwdietrich

  • Hero Member
  • *****
  • Posts: 1165
    • formatio reticularis
Cross-platform way to get and toggle the Num Lock state
« on: June 29, 2019, 06:56:11 pm »
Is there a cross-platform method for reading and setting the Num Lock state on the numeric keypad available? My application should activate Num Lock on launch or activation and restore the pre-launch state on terminating or when being deactivated.

The solution should be cross-platform compatible to Windows and Linux (macOS not necessary, where Num Lock is always on).
function GetRandomNumber: integer; // xkcd.com
begin
  GetRandomNumber := 4; // chosen by fair dice roll. Guaranteed to be random.
end;

http://www.formatio-reticularis.de

Lazarus 2.0.10 | FPC 3.2.0 | PPC, Intel, ARM | macOS, Windows, Linux

jwdietrich

  • Hero Member
  • *****
  • Posts: 1165
    • formatio reticularis
Re: Cross-platform way to get and toggle the Num Lock state
« Reply #1 on: July 02, 2019, 10:49:34 pm »
Well, I think it has reasons that this thread doesn't get a reply.

I learned that setting the num lock state requires administrating privileges and isn't part of the userland API, at least in Windows (see e.g. https://stackoverflow.com/questions/25724740/getting-and-setting-numlock-state-in-lazarus). In my opinion, this doesn't make sense, since this is nothing than an issue of the user interface, but this decision has been made long ago.

I now changed the design of my app, so that it reads the num lock state and provides a warning if num lock is deactivated.

For those who are interested, the following method changes the colour of a small circular shape (NumLockIndicator to be similar to a little LED) to red or green depending on the num lock state:

Code: Pascal  [Select][+][-]
  1. procedure TMainForm.IndicateNumLockState(Sender: TObject);
  2. begin
  3.   {$IF DEFINED(LCLcarbon) or DEFINED(LCLCocoa)}
  4.     NumLockIndicator.visible := false;
  5.   {$ELSE}
  6.   if Odd(GetKeyState(VK_NUMLOCK)) then
  7.   begin
  8.     NumLockIndicator.Brush.Color := clLime;
  9.     NumLockIndicator.Hint := 'Num Lock is activated. You can enter numbers via the numeric keypad.';
  10.   end
  11.   else
  12.   begin
  13.     NumLockIndicator.Brush.Color := clRed;
  14.     NumLockIndicator.Hint := 'Num Lock is deactivated. Numbers cannot be entered via the numeric keypad.';
  15.   end;
  16.   {$ENDIF}
  17. end;

This code is inspired by https://forum.lazarus.freepascal.org/index.php?topic=12143.0.
function GetRandomNumber: integer; // xkcd.com
begin
  GetRandomNumber := 4; // chosen by fair dice roll. Guaranteed to be random.
end;

http://www.formatio-reticularis.de

Lazarus 2.0.10 | FPC 3.2.0 | PPC, Intel, ARM | macOS, Windows, Linux

 

TinyPortal © 2005-2018