Recent

Author Topic: reading Umlaut characters with KeyPress event  (Read 8368 times)

Martin V

  • Full Member
  • ***
  • Posts: 139
reading Umlaut characters with KeyPress event
« on: July 21, 2010, 02:40:34 pm »
Hello,

I want to read keyboard input with the tControl.Keypress event. Because Lazarus compiles text by default in UTF8 encoding, I have to use this code which works fine in Windows:

Code: [Select]
procedure tMyForm.UTF8KeyPress(var UTF8Key: TUTF8Char);
  var
    Key : char;
    St : ansistring;
  begin
    inherited UTF8KeyPress (UTF8Key);
    St := UTF8ToAnsi (UTF8Key);
    Key := St[1];
    (*here I process the keyboard input in ANSI format*)
   end;

But it does not work in Linux and MacOSX. I haven't managed to read correctly umlaut characters (ANSI Ascii > #127) from the keyboard. Do I need to use another event?

Martin

theo

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 1927
Re: reading Umlaut characters with KeyPress event
« Reply #1 on: July 21, 2010, 03:54:44 pm »
With UTF8ToAnsi you loose Unicode information.

You would need UTF8Decode. Then you get a WideString from it where the first character is what you are looking for (It's a WideChar).

Further processing depends on what you actually want to do with it.

var
St:WideString;
Key:WideChar;
...
begin
St:=UTF8Decode(UTF8Key);
Key:=St[1]; //better check for length first.

Martin V

  • Full Member
  • ***
  • Posts: 139
Re: reading Umlaut characters with KeyPress event
« Reply #2 on: July 21, 2010, 10:48:41 pm »
Theo,
with your solution, I need to convert from WideString to AnsiString again... I've found now a solution direct from UTF8 to Ansi:

Code: [Select]
procedure tMyForm.UTF8KeyPress(var UTF8Key: TUTF8Char);
  var
    Key : char;
    uSt : utf8string;
    St : ansistring;
  begin
    inherited UTF8KeyPress (UTF8Key);
    uSt := utf8key;
    St := lconvencoding.UTF8ToCP1252 (uSt);
    if length(St) = 1 then begin
      Key := St[1];
      {processing the keyboard character input here}
    end;
  end;

It seems that the UTF8toAnsi and AnsiToUTF8 conversion routines work fine in Windows, but are not specific enough for Unix, because there are different Ansi codepages, and Unix does not know that Windows uses Codepage 1252 by default.

Martin
« Last Edit: July 29, 2010, 05:12:21 pm by Martin V »

theo

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 1927
Re: reading Umlaut characters with KeyPress event
« Reply #3 on: July 21, 2010, 11:28:32 pm »
What do you want with Ansi? Forget Ansi and use Unicode (WideString or UTF8String).
Please describe what you want to achieve.

Martin V

  • Full Member
  • ***
  • Posts: 139
Re: reading Umlaut characters with KeyPress event
« Reply #4 on: July 25, 2010, 07:03:38 pm »
I am porting an existing project to Lazarus. I will move all strings to UTF8 later. If I would write a new application, UTF8 would be the first choice.

Martin

 

TinyPortal © 2005-2018