Recent

Author Topic: Cannot cancel Enter key press on TEdit  (Read 598 times)

leduyquang753

  • Newbie
  • Posts: 2
Cannot cancel Enter key press on TEdit
« on: May 04, 2019, 04:02:05 pm »
I am making an expression parser with an input box (TEdit) that when a mistake is present in the expression, the caret moves to where it is. So I hook OnKeyPress to the TEdit:

Code: Pascal  [Select]
  1. procedure TMainWindow.ExpressionKeyPress(Sender: TObject; var Key: char);
  2. begin
  3.   if key = #13 then begin
  4.     self.calculateIt; // This moves the caret when an error happens.
  5.     key := #0; // Supposed to cancel the key press.
  6.   end;
  7. end;

When an erroneous expression is entered, the caret is seen to be moved to the mistake's location, however shortly after, the whole text in the box is selected, which indicates the Enter key was not canceled, despite having the code to do so.

I tried these workarounds:
  • Hooking an additional OnKeyDown event to cancel the key.
  • Setting TForm.KeyPreview to true.
None of them worked.

Am I doing something wrong or is there a bug in LCL/Windows OS?
« Last Edit: May 04, 2019, 04:06:00 pm by leduyquang753 »

Thaddy

  • Hero Member
  • *****
  • Posts: 9298
Re: Cannot cancel Enter key press on TEdit
« Reply #1 on: May 04, 2019, 04:34:58 pm »
I tried these workarounds:
  • Hooking an additional OnKeyDown event to cancel the key.
  • Setting TForm.KeyPreview to true.
None of them worked.

Am I doing something wrong or is there a bug in LCL/Windows OS?


Try using OnKeyUp, because only then you can evaluate correctly. (This is a very common error)
« Last Edit: May 04, 2019, 04:37:27 pm by Thaddy »
also related to equus asinus.

Bart

  • Hero Member
  • *****
  • Posts: 3548
    • Bart en Mariska's Webstek
Re: Cannot cancel Enter key press on TEdit
« Reply #2 on: May 04, 2019, 06:19:42 pm »
Use OnEditingDone for that (it is fired when user presses Enter or when user leaves the control).

Bart

Thaddy

  • Hero Member
  • *****
  • Posts: 9298
Re: Cannot cancel Enter key press on TEdit
« Reply #3 on: May 04, 2019, 07:32:34 pm »
Use OnEditingDone for that (it is fired when user presses Enter or when user leaves the control).

Bart
No.
also related to equus asinus.

jamie

  • Hero Member
  • *****
  • Posts: 2173
Re: Cannot cancel Enter key press on TEdit
« Reply #4 on: May 04, 2019, 11:11:19 pm »
I assume you set "Autofocus" := False ?
Number 1 at blue screen app creations!

leduyquang753

  • Newbie
  • Posts: 2
Re: Cannot cancel Enter key press on TEdit
« Reply #5 on: May 05, 2019, 02:47:59 am »
Try using OnKeyUp, because only then you can evaluate correctly. (This is a very common error)

Oh, the key release event is also triggered. You made my day, thank you.