SetFocus is a method that is defined in the
TWinControl class (only window controls can have focus). In your code, the variable
Component is declared as a
String type.
String is a simple type, it doesn't have built-in methods and properties like classes. That's why the compiler throws an error. Also, focus can only be set for controls that are windowed. That's why it's better to use the
Controls property instead of the
Components property (components are often invisible). So the code should be as follows:
procedure TForm1.Button1Click(Sender: TObject);
var
i, ATotalCount: Integer;
AControl: TControl;
begin
// display the total number of components in a message box
ATotalCount := Form1.ControlCount;
ShowMessage('Total components on form: ' + ATotalCount.ToString);
// optionally, you can loop through the components
Memo1.Lines.Clear;
for i := 0 to Self.ControlCount - 1 do
begin
Memo1.Lines.Add('Component ' + (i + 1).ToString + ': ' + Form1.Controls[i].Name);
end;
// focus on the last control if it is a windowed control
AControl := Form1.Controls[ATotalCount - 1];
if AControl is TWinControl
then (AControl as TWinControl).SetFocus;
end;
Edit: I included a simple project using the example provided.