2008. február 29., péntek

Change the font of all controls on a form at runtime


Problem/Question/Abstract:

How to change the font of all controls on a form at runtime

Answer:

By default all controls have ParentFont = true, so if you did not change that for specific controls you could just change the forms Font property, e.g. in code attached to the Screen.OnActiveFormChange event. If you cannot rely on all controls having Parentfont = true you would have to loop over all controls on the form and set the font property for each or at least for those that have ParentFont set to false. You can use the routines from unit TypInfo for that, they allow you to access published properties by name. The code, again sitting in a handler for Screen.onActiveFormChange, would be something like this:

ModifyFontsFor(Screen.ActiveControl);

where

procedure ModifyFontsFor(ctrl: TWinControl);

  procedure ModifyFont(ctrl: TControl);
  var
    f: TFont;
  begin
    if IsPublishedProp(ctrl, 'Parentfont') and (GetOrdProp(ctrl, 'Parentfont') =
      Ord(false)) and IsPublishedProp(ctrl, 'font') then
    begin
      f := TFont(GetObjectProp(ctrl, 'font', TFont));
      f.Name := 'Symbol';
    end;
  end;

var
  i: Integer;
begin
  ModifyFont(ctrl);
  for i := 0 to ctrl.controlcount - 1 do
    if ctrl.controls[i] is TWinControl then
      ModifyFontsfor(TWinControl(ctrl.controls[i]))
    else
      Modifyfont(ctrl.controls[i]);
end;

Remember to add TypInfo to your uses clause.

Nincsenek megjegyzések:

Megjegyzés küldése