如何在其父级接收并失去Delphi焦点时通知控件?

iMa*_*ari 5 delphi components vcl

正如标题所说,我想要一个组件(例如,a label)在它的父母(比方说,a panel)收到并失去焦点时得到通知.我在Delphi源代码中漫游,希望使用TControl.Notify它,但它只用于通知子控件的某些属性更改,如字体和颜色.有什么建议?

NGL*_*GLN 7

每当应用程序中的活动控件发生更改时,CM_FOCUSCHANGED都会向所有控件广播一条消息.简单地拦截它,并采取相应的行动.

此外,我假设当它的父(例如,一个面板)接收并失去焦点时,你的意思是每当该父/面板上的(嵌套)子控件接收或失去焦点时.

type
  TLabel = class(StdCtrls.TLabel)
  private
    function HasCommonParent(AControl: TWinControl): Boolean;
    procedure CMFocusChanged(var Message: TCMFocusChanged);
      message CM_FOCUSCHANGED;
  end;

procedure TLabel.CMFocusChanged(var Message: TCMFocusChanged);
const
  FontStyles: array[Boolean] of TFontStyles = ([], [fsBold]);
begin
  inherited;
  Font.Style := FontStyles[HasCommonParent(Message.Sender)];
end;

function TLabel.HasCommonParent(AControl: TWinControl): Boolean;
begin
  Result := False;
  while AControl <> nil do
  begin
    if AControl = Parent then
    begin
      Result := True;
      Break;
    end;
    AControl := AControl.Parent;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

如果你不喜欢子类TJvGradientHeader,那么可以通过使用以下方式来设计它Screen.OnActiveControlChange:

  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    FHeaders: TList;
    procedure ActiveControlChanged(Sender: TObject);
  end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FHeaders := TList.Create;
  FHeaders.Add(Label1);
  FHeaders.Add(Label2);
  Screen.OnActiveControlChange := ActiveControlChanged;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FHeaders.Free;
end;

function HasCommonParent(AControl: TWinControl; AMatch: TControl): Boolean;
begin
  Result := False;
  while AControl <> nil do
  begin
    if AControl = AMatch.Parent then
    begin
      Result := True;
      Break;
    end;
    AControl := AControl.Parent;
  end;
end;

procedure TForm1.ActiveControlChanged(Sender: TObject);
const
  FontStyles: array[Boolean] of TFontStyles = ([], [fsBold]);
var
  I: Integer;
begin
  for I := 0 to FHeaders.Count - 1 do
    TLabel(FHeaders[I]).Font.Style :=
      FontStyles[HasCommonParent(Screen.ActiveControl, TLabel(FHeaders[I]))];
end;
Run Code Online (Sandbox Code Playgroud)

请注意,我选择TLabel演示此作品也适用于TControl衍生品.