1. Technology

How to Translate a Virtual Key Code to a Character


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;
    keyboardState: TKeyboardState;
    asciiResult: Integer;
    GetKeyboardState(keyboardState) ;
    SetLength(Result, 2) ;
    asciiResult := ToAscii(key, MapVirtualKey(key, 0), keyboardState, @Result[1], 0) ;
    case asciiResult of
      0: Result := '';
      1: SetLength(Result, 1) ;
        Result := '';
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) ;
    Self.Caption := GetCharFromVirtualKey(Key) ;

Delphi tips navigator:
» Programmatically Get and Set the State of the CapsLock and NumLock Keys
« Add Your Application to the Windows "Send To" Menu

  1. About.com
  2. Technology
  3. Delphi
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2006 Tips
  7. How to Translate a Virtual Key Code to a Character in Delphi Keyboard Event Handlers

©2014 About.com. All rights reserved.