Search code examples
delphidelphi-7keyboard-eventsvcl

Delphi remap key to multi characters


I want that when I press a M or m character, 000000 gets input on a specific TEdit box:

procedure Tfrm.FormKeyPress(Sender: TObject; var Key: Char) ;
var
  i : integer;
begin
  if Key in ['m'] + ['M'] then Key := '0';
end;

With this code, I can just remap 'M' key to single character. How can I remap 'M' to multiple characters for a TEdit box?


Solution

  • Use the OnKeyPress event of the TEdit itself, not the OnKeyPress event of the parent TForm. Set the Key parameter to #0 to swallow it, and then insert 6 individual '0' characters into the TEdit:

    procedure Tfrm.Edit1KeyPress(Sender: TObject; var Key: Char);
    var
      i : integer;
    begin
      if Key in ['m', 'M'] then
      begin
        Key := #0;
        for I := 1 to 6 do
          Edit1.Perform(WM_CHAR, Ord('0'), $80000001);
      end;
    end;
    

    Alternatively:

    procedure Tfrm.Edit1KeyPress(Sender: TObject; var Key: Char);
    begin
      if Key in ['m', 'M'] then
      begin
        Key := #0;
        Edit1.SelText := '000000';
      end;
    end;