Preview All Installed Fonts

From IronPython Cookbook

Preview All Installed Fonts

A simple WinForms app that shows you how to preview all of the fonts installed on your system. Uses LisBox, TextBox, ComboBox, and StatusBar. Also shows the usage of some events.

Font Previewer App

import clr
clr.AddReference("System.Drawing")
clr.AddReference('System.Windows.Forms')
from System.Drawing import Font, FontStyle
from System.Drawing.Text import InstalledFontCollection
from System.Windows.Forms import (Form, Button, BorderStyle, DockStyle,
                                  ListBox, ComboBox, TextBox, StatusBar)

fontCollection = InstalledFontCollection()
fonts = [f for f in fontCollection.Families]

f = Form()
f.Text = 'Font Previewer'
f.Width = 800
f.Height = 600

lb = ListBox()
lb.Width = 230
for font in fonts:
    lb.Items.Add(font.Name)
lb.SelectedIndex = 0    

cbSizes = ComboBox()
for i in range(9, 49):
    cbSizes.Items.Add(str(i))
cbSizes.Text = '30'

cbStyles = ComboBox()
for s in ['Regular', 'Bold', 'Italic']:
    cbStyles.Items.Add(s)
cbStyles.Text = 'Regular'

tb = TextBox()
tb.Font = Font(fonts[0], 30)
tb.Multiline = True
tb.Text = u"Hello World!\r\n\u4f60\u597d\u4e16\u754c\uff01"

sb = StatusBar()
sb.Text = 'Found %d installed fonts' % len(fonts)

# Layout:
lb.Dock = DockStyle.Left
tb.Dock = DockStyle.Fill
cbSizes.Dock = DockStyle.Top
cbStyles.Dock = DockStyle.Top
sb.Dock = DockStyle.Bottom
f.Controls.Add(tb)
f.Controls.Add(cbStyles)
f.Controls.Add(cbSizes)
f.Controls.Add(lb)
f.Controls.Add(sb)
f.ActiveControl = lb

# Event handling
def ChangeFont():
    try:
        tb.Font = Font(fonts[lb.SelectedIndex],
                       int(cbSizes.Text),
                       getattr(FontStyle, cbStyles.Text))
        sb.Text = ''
    except Exception,e:
        sb.Text = unicode(e)
        
lb.SelectedIndexChanged += lambda sender, args: ChangeFont()
cbSizes.TextChanged += lambda sender, args: ChangeFont()
cbStyles.TextChanged += lambda sender, args: ChangeFont()

f.ShowDialog()


Back to Contents.

TOOLBOX
LANGUAGES