Search code examples
lazarusdelphi

Remove delay when continuously pressing a key


I want to move an image when I press a button, Up, but there is a slight delay:

Assuming I continuously hold down Up, the image moves up, stops for ~1s, and then goes up continuously.

I want to remove that 1s delay. I read that I can use GetAsyncKeyState, but because I'm on Linux this win32 function is not available. Also, a cross platform solution is better.

This is currently my code:

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_LEFT then
      Image1.Left := Image1.Left - 1
  else if Key = VK_RIGHT then
      Image1.Left := Image1.Left + 1;
end;

So, how can I solve this problem?


Solution

  • You can use get GetKeyState function included in LCLIntf. It calls the Win32 API function GetKeyState on Windows, and there is a custom implementation on other platforms. And so it is cross-platform.

    procedure TForm1.checkKeyboard();
    begin
        // When a key is down, the return value of GetKeyState has the high bit set,
        // making the result negative.
        if GetKeyState(VK_LEFT) < 0 then
            moveLeft(); // whatever
        //...
    end;