VB.NET: how to compose and apply a font to a label at runtime?

I am developing a Windows Forms application in Visual Basic.NET with Visual Studio 2008.

I am trying to create fonts (last name, font size and styles) at runtime based on user preferences and apply them to shortcuts.

Both for a simpler user interface and for compatibility between several machines requiring the use of the same font, I DO NOT use InstalledFontCollection , but a set of buttons that will install several selected fonts that, as I know, are present on all machines ( fonts like Verdana).

So, I have to make Public Sub on a module that will create fonts, but I don't know how to encode it. There are also four CheckBoxes that set styles, Bold, Italic, Underline, and Strikeout.

How do I encode this? The SomeLabel.Font.Bold property is read-only, and there seems to be a problem converting a string like Times New Roman to FontFamily. (He just says he can't do it)

How on

Dim NewFontFamily As FontFamily = "Times New Roman"

Thanks in advance.

+7
source share
1 answer

This should solve your font problem:

Label1.Font = New Drawing.Font("Times New Roman", _
                               16,  _
                               FontStyle.Bold or FontStyle.Italic)

The MSDN documentation for the Font property is here.

A possible implementation of the function that creates this font might look like this:

Public Function CreateFont(ByVal fontName As String, _
                           ByVal fontSize As Integer, _
                           ByVal isBold As Boolean, _
                           ByVal isItalic As Boolean, _
                           ByVal isStrikeout As Boolean) As Drawing.Font

    Dim styles As FontStyle = FontStyle.Regular

    If (isBold) Then
        styles = styles Or FontStyle.Bold
    End If

    If (isItalic) Then
        styles = styles Or FontStyle.Italic
    End If

    If (isStrikeout) Then
        styles = styles Or FontStyle.Strikeout
    End If

    Dim newFont As New Drawing.Font(fontName, fontSize, styles)
    Return newFont

End Function

, , . , .

+11

All Articles