Search code examples
firemonkeysetfocus

Keep a user in a TEdit


I have to check a value of TEdit->Text when a user leaves it and return him to the TEdit, if the value is wrong. The code below works nice in a VCL but it doesn't work in a FMX. So it beeps but doesn't return.

void __fastcall TForm1::Edit1Exit(TObject *Sender)
{
if (Edit1->Text != "123")
    {
    Beep();
    Edit1->SetFocus();
    }
}

It is in a simple form with 2 TEdits only. What I do wrong and how to do it right?


Solution

  • I'll provide a solution in Delphi Firemonkey. Hopefully, the same principles apply in C++ Firemonkey. The following code replaces the invalid text in Edit1 with the word 'Invalid' and returns the focus to Edit1, with 'Invalid' selected ready for overtyping.

    procedure TForm1.Edit1Validate(Sender: TObject; var Text: string);
    begin
      if Text <> '123' then
      begin
        Text := 'Invalid';
        TThread.CreateAnonymousThread(
        procedure
          begin
            TThread.Synchronize(nil,
             procedure
              begin
                Edit1.SetFocus;
              end);
          end).Start;
      end;
    end;