0

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?

Al C
  • 5,175
  • 6
  • 44
  • 74
  • Use the KeyDown event instead. – Olivier Dec 02 '20 at 17:40
  • @Olivier That works! If you'll post a response, maybe with brief explanation about why one uses the KeyDown vs KeyPress event, I'll mark it as the solution. Thank you! – Al C Dec 02 '20 at 17:47
  • Although this may be helpful to me and those coming to this question: https://stackoverflow.com/questions/3396754/onkeypress-vs-onkeyup-and-onkeydown – Al C Dec 02 '20 at 17:50
  • Yep your question can be considered a duplicate of that one (although it's about JS, but the concept is the same). F5 is not a character. – Olivier Dec 02 '20 at 17:53

1 Answers1

2

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;
Tav
  • 336
  • 1
  • 6
  • It's weird that the KeyPress event still recognizes VK_ESCAPE. – Al C Dec 02 '20 at 18:05
  • 2
    @AlC Escape is not a regular character but it's a [control character](https://en.wikipedia.org/wiki/Control_character) (with ASCII code 27). – Olivier Dec 02 '20 at 18:13