AdvancedCharacterControl (Delphi)
Contents
Description
The following example demostrates the use of some advanced method in the Character unit. An edit box is configured to allow 2 unicode characters (since there may be surrogate pairs).
Code
procedure TMainForm.edtCharChange(Sender: TObject);
var
U4: UCS4Char;
Cat: TUnicodeCategory;
Value: String;
begin
Value := edtChar.Text;
{ Do nothing on empty edit }
if Value = '' then
Exit;
{ Note that 2 characters may represent a surrogate pair! }
{ Only allow control codes and alpha-numeric values in }
if (not IsLetterOrDigit(Value[1])) and
(not Character.IsControl(Value[1]) and
(not IsSurrogate(Value[1])))
then Exit;
{ Covert the entered char to UCS4 }
U4 := ConvertToUtf32(Value, 1);
{ And now convert back }
if (ConvertFromUtf32(U4) <> Value) then
MessageDlg('Cannot happen!', mtError, [mbOK], 0);
MessageDlg('The numeric value of the character is ' +
FloatToStr(GetNumericValue(Value[1])), mtInformation, [mbOK], 0);
{ Get the unicode category of the character }
Cat := GetUnicodeCategory(Value[1]);
MessageDlg(Format('The character "%s" category is: %s ',
[Value[1], GetEnumName(TypeInfo(TUnicodeCategory), Ord(Cat))]),
mtInformation, [mbOK], 0);
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
{ Allow two characters to be typed into
the edit box. In case of Unicode surrogates,
2 characters represent one real character.
}
edtChar.MaxLength := 2;
end;
Uses
- System.Character.IsLetterOrDigit ( fr | de | ja )
- System.Character.IsControl ( fr | de | ja )
- System.Character.ConvertFromUtf32 ( fr | de | ja )
- System.Character.GetNumericValue ( fr | de | ja )
- System.Character.GetUnicodeCategory ( fr | de | ja )
- System.Character.TUnicodeCategory ( fr | de | ja )
- Vcl.StdCtrls.TCustomEdit.MaxLength ( fr | de | ja )