Search code examples
windowsdelphivcl

How to recognize virtual key codes in KeyPress event?


I am trying to implement something similar to Notepad's insertion of the date and time when users press the F5 key. In the event

procedure TFormMain.Memo1KeyPress(Sender: TObject; var Key: Char);

the code

  if Key=Chr(VK_F5) then
  begin
    Memo1.Lines.Add(FormatDateTime('h:nn',now));
  end;

has no effect. In the same method,

  if Key=Chr(VK_ESCAPE) then
  //do something

does something.

What do I need to do for the application to recognize when users press F5?


Solution

  • From the Help Form TMemo KeyPress Event:

    Keys that do not correspond to an ASCII Char value (SHIFT or F1, for example) do not generate an OnKeyPress event.

    F5 is one of those Keys. Try the OnKeyDown Event instead.

    procedure TForm1.Memo1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    begin
      if Key = VK_ESCAPE then
        Memo1.Lines.Add('Escape')
      else if Key = VK_F5 then
        Memo1.Lines.Add('F5');
    end;