Link to home
Start Free TrialLog in
Avatar of EricTaylor
EricTaylor

asked on

Converting key value in OnKeyDown from Word to Char

For a Delphi form, I'm using OnKeyDown to trap the key that's pressed, and then doing various actions. However, if (key >= 32) and (key <=126) then I need to append the key to a string. Since OnKeyDown returns a Word rather than a char, I need to convert the Word to the ASCII char equivalent (e.g., 65 -> A, etc.) Not wanting to manually write something that manually addresses each possible value (which would work buy which would be kludgey), and not knowing how to do this, I looked online and "borrowed" something like this:
function KeyToStr(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
      1: SetLength(Result, 1);
      2:;
      else Result := '';
    end;
 end;

Open in new window

This mostly works (though I confess to not understanding all of what it's doing), but when I press certain keys (e.g. Backspace consistently does it), when I append to the value to something I can display it in (using a DevExpress TcxEdit... though don't see why that would have a bearing), the characters turn to some seeming random foreign character set (often Chinese but not always).
Is there a better way to determine the character value of the key and/or can someone tell me how to keep this  from picking some other set of characters?
Avatar of Ferruccio Accalai
Ferruccio Accalai
Flag of Italy image

You could use the OnkeyPress and the OnkeyDOwn combined togeter

OnKeyDown is trapped before of OnKeyPress, so you could just check in the OnKeyPress event any char key and let the other job for OnKeyDown

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  Showmessage(Format('KeyValue = %d', [Key]));
end;

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
  // check if the key is a valid keyboard char
  if (ord(Key) >= 32) and (ord(Key) <=126) then
    Showmessage(Key);
end;
Avatar of EricTaylor
EricTaylor

ASKER

In this case, since OnKeyDown has information about the TshiftState and OnKeyPress doesn't, Whether I want to take action for example, if the A key is pressed, depends on whether ssCtrl or ssAlt are combined with it, so I think I need OnKeyDown rather than OnKeyPress.
ASKER CERTIFIED SOLUTION
Avatar of Ferruccio Accalai
Ferruccio Accalai
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks... didn't know one could cast the key as Char. That did the trick. I knew about handling the shift state, but appreciate the completeness of covering that in your example just in case.