Recent

Author Topic: Cannot cancel Enter key press on TEdit  (Read 994 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: 10492
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 »
When you ask a question that is actually answered in the documentation, you are either lazy or a moron.

Bart

  • Hero Member
  • *****
  • Posts: 3919
    • 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: 10492
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.
When you ask a question that is actually answered in the documentation, you are either lazy or a moron.

jamie

  • Hero Member
  • *****
  • Posts: 3542
Re: Cannot cancel Enter key press on TEdit
« Reply #4 on: May 04, 2019, 11:11:19 pm »
I assume you set "Autofocus" := False ?
The only true wisdom is knowing you know nothing

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.

 

TinyPortal © 2005-2018