Forum > LCL
reading Umlaut characters with KeyPress event
(1/1)
Martin V:
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: ---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;
--- End code ---
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:
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:
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: ---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;
--- End code ---
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
theo:
What do you want with Ansi? Forget Ansi and use Unicode (WideString or UTF8String).
Please describe what you want to achieve.
Martin V:
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
Navigation
[0] Message Index