2010. december 13., hétfő

Implement the equivalent of TForm.OnCreate for a TFrame


Problem/Question/Abstract:

I miss one thing in frames: The ability of performing some initialization code as I would do in a TForm.OnCreate. So what would be the equivalent for frames?

Answer:

You can override the constructor for example. An alternative is to override the SetParent method and do the initialization after calling the inherited method. This way the frame will have a parent and you can then do things that require a window handle without running into problems. I use a base frame class in my current project that has this feature build in. The relevant parts are given below. In descendents I just override the Initialize method.

{ ... }
type
  {The base class for frames}
  TPLC_BaseFrame = class(TFrame)
  protected
    procedure SetParent(aParent: TWinControl); override;
  public
    procedure Initialize; virtual;
    procedure UnInitialize; virtual;
    destructor Destroy; override;
  end;

procedure TPLC_BaseFrame.Initialize;
begin
  {Override as needed in descendents}
end;

procedure TPLC_BaseFrame.UnInitialize;
begin
  {Override as needed in descendents}
end;

procedure TPLC_BaseFrame.SetParent(aParent: TWinControl);
var
  oldparent: TWinControl;
begin
  oldparent := Parent;
  inherited;
  if (oldparent = nil) and (aParent <> nil) then
    Initialize;
end;

destructor TPLC_BaseFrame.Destroy;
begin
  Uninitialize;
  inherited;
end;

Nincsenek megjegyzések:

Megjegyzés küldése