2009. augusztus 9., vasárnap

Get the name of a keyboard key


Problem/Question/Abstract:

Does anyone know how to get the name of a key from the keyboard? I want a method that sends the ASCII code and returns the correct name in string format.

Answer:

Start with calling VkKeyScan, then proceed to GetKeynameText, via MapVirtualKey.

function GetKeyname(ch: Char): string;
var
  scan: Word;
  virtual_keycode: Byte;
  keyname: array[0..128] of Char;
  lparam: Integer;
begin
  scan := VkKeyScan(ch);
  Result := '';
  if scan <> $FFFF then
  begin
    if (Scan and $100) <> 0 then
      Result := Result + '[Shift]';
    if (Scan and $200) <> 0 then
      Result := Result + '[Ctrl]';
    if (Scan and $400) <> 0 then
      Result := Result + '[Alt]';
    virtual_keycode := Lobyte(scan);
    lparam := MapVirtualKey(virtual_keycode, 0) shl 16;
    if lparam <> 0 then
      if GetKeyNametext(lparam, keyname, sizeof(keyname)) > 0 then
        Result := Result + '[' + keyname + ']';
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  memo1.text := GetKeyname(alignededit1.text[1]);
end;

Nincsenek megjegyzések:

Megjegyzés küldése