Recent

Author Topic: Detecting symbol corresponding with key value in onKeyPress event.  (Read 401 times)

Tommi

  • Full Member
  • ***
  • Posts: 236
In onKeyPress the value key is returned. It represents the key pressed on keyboard, but corresponding symbol depends on keyboard layout.

I would need to understand if symbol appearing on TMemo is '/' or '+' etc.

Is it possible ?

Thank you

Bart

  • Hero Member
  • *****
  • Posts: 5564
    • Bart en Mariska's Webstek
Re: Detecting symbol corresponding with key value in onKeyPress event.
« Reply #1 on: April 22, 2025, 10:07:23 pm »
The Key parameter of the OnKeyPress event is a Char: it is the "symbol" that (in your example) is typed into the memo.
I think you are confused with OnKeyDown, where the Key parameter is of type word, and it'll be the same Key for (on my keyboard) eithe '+' or '='.

So, if you do not want to allow the user to e.g. type a '@' symbol in your memo, you check for that in OnKeyPress and if Key equals '@', you set Key to #0, in effect discarding the input.

Normally You would use OnKeyPress (and OnUtf8KeyPress) for "printable" characters (symbols) and OnKeyDown for e.g. detecting function keys, arrow keys, delete key etc.

Bart

n7800

  • Sr. Member
  • ****
  • Posts: 296
Re: Detecting symbol corresponding with key value in onKeyPress event.
« Reply #2 on: April 22, 2025, 11:35:04 pm »
In other words, if you want to get the character that will appear in the TMemo, use OnKeyPress. It is usually used to filter input, for example, to only allow numbers when entering a phone number (example is not complete):

Code: Pascal  [Select][+][-]
  1. procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: char);
  2. begin
  3.   if not (Key in ['0'..'9']) then
  4.     Key := #0;
  5. end;
  6.  

By the way, it is better to use the UTF8KeyPress event, which will allow you to get characters of national alphabets.



If you need to know the key itself (regardless of the current keyboard layout), use OnKeyDown. It is usually used to handle key shortcuts:

Code: Pascal  [Select][+][-]
  1. procedure TForm1.Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
  2. begin
  3.   if (Key = VK_RETURN) and (Shift = [ssCtrl]) then // Ctrl+Enter
  4.   begin
  5.     ShowMessage('test');
  6.     Key := 0;
  7.   end;
  8. end;
  9.  

Key constants (VK_) can be found in the LCLType unit. Pay attention to the comments to them, some keys may depend on the standard keyboards in each country.

Assigning zero here is necessary so that this key is not passed on further. For example, you can reassign the combination in TMemo itself.

Tommi

  • Full Member
  • ***
  • Posts: 236
Re: Detecting symbol corresponding with key value in onKeyPress event.
« Reply #3 on: April 23, 2025, 10:13:27 am »
OK,
thank you

 

TinyPortal © 2005-2018