正如标题所说,我希望一个组件(例如,标签
)在它是父级(例如,面板
)时得到通知code>) 接收并失去焦点。我在 Delphi 源代码中徘徊了一下,希望使用 TControl.Notify,但它仅用于通知子控件某些属性更改(如字体和颜色)。有什么建议吗?
最佳答案
每当应用程序中的事件控件发生更改时,CM_FOCUSCHANGED
消息就会广播到所有控件。只需拦截它,并采取相应的行动即可。
此外,我假设当它的父级(例如面板)接收和失去焦点时意味着每当该父级/面板上的(嵌套)子控件接收或失去焦点时。 p>
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;
如果您不喜欢子类化 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;
请注意,我选择了 TLabel
来演示这也适用于 TControl
衍生物。
关于delphi - 在 Delphi 中,当其父控件获得和失去焦点时,如何通知控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12437529/