I am migrating a VCL application to FMX. I need to know the class of a control that has focus. The application works with various dynamically created frames with numerous input controls.
In VCL I use the VCL.Forms.TScreen.OnActiveControlChange as this is the one place to consistently capture the active control. This event is not available in FMX.Forms.TScreen. What would be an alternative approach in FMX?
2 Answers
The most similar approach in FMX would be to listen to the TForm.OnFocusChanged event. From within the event handler you could then look up theTForm.Focused property.
2 Comments
Sadly in Delphi 10.3, the approach outlined by @iamjoosy fails spectacularly with an 'Access Violation' under certain circumstances (especially when TabControls / TabItems are used as containers for other controls).
The code I am using:
procedure TForm1.FormFocusChanged(Sender: TObject); var Control : iControl; MyControl : TFMXObject; begin Control := form1.focused; try MyControl := TFmxObject(Control.GetObject); form1.Caption := MyControl.Name + ' of type ' + MyControl.ClassName; finally MyControl := nil; Control := nil; end; end; Yet to add some intrigue, the above approach reverts to working fine if:
1) There's no TabControl/TabItem objects
2) If I add the following event handler to each child button (e.g. setting focus back to its parent TabItem):
procedure TForm1.Button2Click(Sender: TObject); begin TabItem1.SetFocus; end; Hoping someone can offer advice as to whether I'm doing something stupid, or whether I've run into an FMX bug.