1. Home
  2. Computing & Technology
  3. Delphi Programming

How to Translate a Virtual Key Code to a Character

By , About.com Guide

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;

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

More Delphi Programming Quick Tips
Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  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

©2009 About.com, a part of The New York Times Company.

All rights reserved.