Mega Code Archive

 
Categories / Delphi / Examples
 

Change the font for all controls at run-time

{ Question: What is the most easy way to set a same font name to all controls in project in run time? 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; procedure TForm1.Button2Click(Sender: TObject); begin Modifyfontsfor(self); end; // Remember to add TypInfo to your uses clause.