While working on one of my Xojo projects, I needed a quick way to change the font used by the controls across the entire application.
Opening every window and updating each control individually works, but it gets tedious quickly, especially when testing different fonts or adding new UI elements. So I created a small module that applies a font to all supported controls in a DesktopWindow, including controls placed inside DesktopContainer instances.
Module AppWideFont
Public Sub SetFont(Extends window As DesktopWindow, fontName As String)
ApplyFontTo(window.Controls, fontName)
End Sub
Protected Function GetMonospaceFont() As String
#If TargetWindows
Return "Cascadia Mono"
#ElseIf TargetMacOS
Return "Menlo"
#ElseIf TargetLinux
Return "DejaVu Sans Mono"
#Else
Return "Courier New"
#EndIf
End Function
Private Sub ApplyFontTo(controls As Iterable, fontName As String)
For Each c As Object In controls
If c IsA DesktopContainer Then
ApplyFontTo(DesktopContainer(c).Controls, fontName)
End If
Select Case c
Case IsA DesktopLabel
DesktopLabel(c).FontName = fontName
Case IsA DesktopTextField
DesktopTextField(c).FontName = fontName
Case IsA DesktopTextArea
DesktopTextArea(c).FontName = fontName
Case IsA DesktopListBox
DesktopListBox(c).FontName = fontName
Case IsA DesktopButton
DesktopButton(c).FontName = fontName
Case IsA DesktopCheckBox
DesktopCheckBox(c).FontName = fontName
Case IsA DesktopRadioButton
DesktopRadioButton(c).FontName = fontName
Case IsA DesktopPopupMenu
DesktopPopupMenu(c).FontName = fontName
End Select
Next
End Sub
End Module
The SetFont method is an extension method, so I can call it directly on any DesktopWindow.
For example, in a window’s Opening event:
Self.SetFont("Arial")
Or, if I want to use a monospace font:
Self.SetFont(AppWideFont.GetMonospaceFont)
The GetMonospaceFont function is just a simple additional helper that returns a suitable monospace font for Windows, macOS, or Linux.
The module uses the window’s Controls collection and recursively checks any DesktopContainer controls, so I only need one line of code per window. It currently handles labels, text fields, text areas, list boxes, buttons, checkboxes, radio buttons, and popup menus.
If I add another control type later, I can extend the Select Case statement with another branch.
This saved me from repeatedly changing font settings throughout the project and gave me one central place to control the application’s typography.
Gabriel is a digital marketing enthusiast who loves coding with Xojo to create cool software tools for any platform. He is always eager to learn and share new ideas!
