在Delphi表单上递归更新字体
时间:2020-03-06 14:59:18 来源:igfitidea点击:
我正在尝试迭代表单上的所有控件并启用ClearType字体平滑。像这样的东西:
procedure TForm4.UpdateControls(AParent: TWinControl); var I: Integer; ACtrl: TControl; tagLOGFONT: TLogFont; begin for I := 0 to AParent.ControlCount-1 do begin ACtrl:= AParent.Controls[I]; // if ParentFont=False, update the font here... if ACtrl is TWinControl then UpdateControls(Ctrl as TWinControl); end; end;
现在,有没有一种简单的方法来检查ACtrl
是否具有Font
属性,因此我可以将Font.Handle
传递给类似这样的对象:
GetObject(ACtrl.Font.Handle, SizeOf(TLogFont), @tagLOGFONT); tagLOGFONT.lfQuality := 5; ACtrl.Font.Handle := CreateFontIndirect(tagLOGFONT);
先感谢我们。
解决方案
我们使用TypInfo单位,更具体地说,使用方法IsPublishedProp和GetOrdProp。
在情况下,可能是这样的:
if IsPublishedProp(ACtrl, 'Font') then ModifyFont(TFont(GetOrdProp(ACtrl, 'Font')))
来自我的一个库的片段,应该使我们走上正确的道路:
function ContainsNonemptyControl(controlParent: TWinControl; const requiredControlNamePrefix: string; const ignoreControls: string = ''): boolean; var child : TControl; iControl: integer; ignored : TStringList; obj : TObject; begin Result := true; if ignoreControls = '' then ignored := nil else begin ignored := TStringList.Create; ignored.Text := ignoreControls; end; try for iControl := 0 to controlParent.ControlCount-1 do begin child := controlParent.Controls[iControl]; if (requiredControlNamePrefix = '') or SameText(requiredControlNamePrefix, Copy(child.Name, 1, Length(requiredControlNamePrefix))) then if (not assigned(ignored)) or (ignored.IndexOf(child.Name) < 0) then if IsPublishedProp(child, 'Text') and (GetStrProp(child, 'Text') <> '') then Exit else if IsPublishedProp(child, 'Lines') then begin obj := TObject(cardinal(GetOrdProp(child, 'Lines'))); if (obj is TStrings) and (Unwrap(TStrings(obj).Text, child) <> '') then Exit; end; end; //for iControl finally FreeAndNil(ignored); end; Result := false; end; { ContainsNonemptyControl }
无需为此使用RTTI。每个TControl后代都有一个Font属性。在TControl级别,其可见性受到保护,但我们可以使用以下解决方法来访问它:
type THackControl = class(TControl); ModifyFont(THackControl(AParent.Controls[I]).Font);
另一件事值得一提。每个控件都有一个ParentFont属性,如果设置了该属性,则允许窗体的字体选择波及到每个控件。我倾向于确保在任何可能的地方将ParentFont设置为true,这也使得根据当前OS主题化表单变得更加容易。
无论如何,我们肯定不需要做任何事情来启用ClearType平滑吗?如果我们使用TrueType字体并且用户启用了Cleartype"效果",它应该会自动发生。