AdvancedTCharacterControl (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following example demostrates the use of some advanced method in the TCharacter class. An edit box is configured to allow 2 unicode characters (since there may be surrogate pairs).

Code

__fastcall TMainForm::TMainForm(TComponent* Owner)
	: TForm(Owner)
{
	/* Allow two characters to be typed into
	the edit box. In case of Unicode surrogates,
	2 characters represent one real character.
	*/
	edtChar->MaxLength = 2;
}

void __fastcall TMainForm::edtCharChange(TObject *Sender)
{
	UCS4Char u4;
	TUnicodeCategory cat;
	String value;

	value = edtChar->Text;

	/* Do nothing on empty edit */
	if (value == "")
		return;

	/* Note that 2 characters may represent a surrogate pair!
	 Only allow control codes and alpha-numeric values in */
	if (!Character::IsLetterOrDigit(value[1]) &&
		!Character::IsControl(value[1]) &&
		!IsSurrogate(value[1]))
		return;

	/* Covert the entered char to UCS4 */
	u4 = ConvertToUtf32(value, 1);

	/* And now convert back */
	if (ConvertFromUtf32(u4) != value)
		MessageDlg("Cannot happen!", mtError, TMsgDlgButtons() << mbOK, 0);

	MessageDlg("The numeric value of the character is " +
		FloatToStr(GetNumericValue(value[1])), mtInformation, TMsgDlgButtons() << mbOK, 0);

	/* Get the unicode category of the character */
	cat = GetUnicodeCategory(value[1]);

	MessageDlg(Format("The character '%s' category is: %d ",
		ARRAYOFCONST((value[1], cat))), mtInformation, TMsgDlgButtons() << mbOK, 0);
}

Uses