Mega Code Archive

 
Categories / Delphi / Hardware
 

How to Translate a Virtual Key Code to a Character in Delphi Keyboard Event Handlers

Title: How to Translate a Virtual Key Code to a Character in Delphi Keyboard Event Handlers Windows defines special constants for each key the user can press. The virtual-key codes identify various virtual keys. These constants can then be used to refer to the keystroke when using Delphi and Windows API calls or in an OnKeyUp or OnKeyDown event handler. The OnKeyDown and OnKeyUp events provide the lowest level of keyboard response. Both OnKeyDown and OnKeyUp handlers can respond to all keyboard keys, including function keys and keys combined with the Shift, Alt, and Ctrl keys. The "Key" parameter in the OnKeyDown (or OnKeyUp) event handler is a virtual key code. Here's how to translate it to a character: function GetCharFromVirtualKey(Key: Word): string; var keyboardState: TKeyboardState; asciiResult: Integer; begin GetKeyboardState(keyboardState) ; SetLength(Result, 2) ; asciiResult := ToAscii(key, MapVirtualKey(key, 0), keyboardState, @Result[1], 0) ; case asciiResult of 0: Result := ''; 1: SetLength(Result, 1) ; 2:; else Result := ''; end; end; Usage example: //Drop a Memo control on a Form and handle its OnKeyDown event as: procedure TForm1.Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState) ; begin Self.Caption := GetCharFromVirtualKey(Key) ; end;