Search code examples
delphifocus

Using ActiveControl property with frames forwarding focus to subcomponents


I have defined a TFrame descendant class and I want to forward the focus to a TEdit subcomponent.

Picture of the frame in the IDE

I've overridden the SetFocus method in order to forward the focus to the edit control:

  TMyFrame = class(TFrame)
    Edit1: TEdit;
  public
    procedure SetFocus(); override;
  end;

...

procedure TMyFrame.SetFocus();
begin
  Edit1.SetFocus();
end;

It works good if I directly call the frame's SetFocus method, but it has no effect when setting the form's ActiveControl property:

var
  Fr : TMyFrame;
begin
  Fr := TMyFrame.Create(Self);
  Fr.Align := alBottom;
  Fr.Parent := Self;

  ActiveControl := Fr;
end;

Solution

  • You have to write either

    ActiveControl := MyFrame1.Edit1;
    

    or

    MyFrame1.Edit1.SetFocus;
    

    If you want to work "at the frame level", you can intercept WM_SETFOCUS in the frame and set focus where you want:

    private
        procedure WMSetFocus(var Msg : TWMSetFocus); message WM_SETFOCUS;
    
    
    procedure TMyFrame.WMSetFocus(var Msg: TWMSetFocus);
    begin
        Edit1.SetFocus;
    end;
    

    When you do that, you can just use

    ActiveControl := MyFrame1;