Posted by Stowaway Im trying to make an application that watches for the arrow key presses. Ive got it working but for some reason it only works when i hold the ALT key down.How can i get around this? procedure
TForm1.FormKeyDown(Sender: TObject; var Key: Word; Answer by Frankie I tested your code and it works as it should. No need to press ALT. In order to have no other stuff that could influence it, test it in a new project with a form with only Label1 and in the unit only the following TForm1.FormKeyDown procedure, so that you can see what is detected in the KeyDown: procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin Label1.Caption := IntToStr(Key) + ' '; case Key of VK_LEFT: Label1.Caption := Label1.Caption + 'LEFT'; VK_RIGHT: Label1.Caption := Label1.Caption + 'RIGHT'; VK_UP : Label1.Caption := Label1.Caption + 'UP'; VK_DOWN: Label1.Caption := Label1.Caption + 'DOWN'; end; end; You never can press 2 keys at exactly the same time. You have to remember the first key that is pressed, and on the next key-press check if that first key is still down. For the 2 keys that you want, you need 2 variables that remember if LEFT or UP are down. The variables are reset with the OnKeyUp event. Here is the code that I tried: var LEFTpressed, UPpressed: Boolean; procedure TForm1.FormCreate(Sender: TObject); begin Label1.Caption := '...'; LEFTpressed := False; UPpressed := False; end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_LEFT: LEFTpressed := True; VK_UP : UPpressed := True; end; ShowKeysPressed; end; procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_LEFT: LEFTpressed := False; VK_UP : UPpressed := False; end; ShowKeysPressed; end; procedure TForm1.ShowKeysPressed; begin if LEFTpressed and UPpressed then Label1.Caption := 'LEFT + UP' else if LEFTpressed then Label1.Caption := 'LEFT' else if UPpressed then Label1.Caption := 'UP' else Label1.Caption := '...'; end;
Good luck! |