I thought I would update my FontDialog script to demonstrate the selected font and style. I discovered that combining multiple font styles is not very intuitive. After selecting the font and it’s characteristics, sample text is displayed with those styles.

FontDialog2

Here are the changes from the original script, excluding some minor rearrangement of the controls in the form.

There are five font styles. I set the style variables to $null, except for $setRegular which I assign the “Regular” FontStyle.

$setBold = $null
$setItalic = $null
$setRegular = [System.Drawing.FontStyle]::Regular
$setStrikeout = $null
$setUnderline = $null

After selecting a font and it’s styles, I check to see if a style has been selected (true) and if so set the FontStyle.

If ($font.Bold -eq "True") {
    $setBold = [System.Drawing.FontStyle]::Bold
}
If ($font.Italic -eq "True") {
    $setItalic = [System.Drawing.FontStyle]::Italic
}
If ($font.Strikeout -eq "True") {
    $setStrikeout = [System.Drawing.FontStyle]::Strikeout
}
If ($font.Underline -eq "True") {
    $setUnderline = [System.Drawing.FontStyle]::Underline
}

A single Font Style is set on a Font like –

$font = New-Object System.Drawing.Font("Comic Sans MS",17,[System.Drawing.FontStyle]::Regular)

For multiple FontStyles it is a bit trickier. FontStyle enumeration has a FlagsAttribute attribute consisting of a set of flags representing the styles. It is a a bitwise combination of the members values to set the attribute. You use -bor to join multiple FontStyle flag bits into the FlagsAttributes byte.

$newFont = New-Object System.Drawing.Font("Comic Sans MS",15,[System.Drawing.FontStyle]([System.Drawing.FontStyle]::Bold -bor [System.Drawing.FontStyle]::Underline))

Since any FontStyle other than Regular replaces Regular and you can -bor null value bits without affecting the byte, I used a single object to filter the styles. I first set Regular flag and then combine the other fours values, letting them fall out if not set. This allows none or any of the FontStyles to be used concurrently but will default to Regular if no addition styles are selected. The only property not set as from the Font Dialog selections is the size, which is fixed for display consistency.

$newFont = New-Object System.Drawing.Font($font.Name,17,[System.Drawing.FontStyle]($setRegular -bor $setBold -bor $setItalic -bor $setStrikeout -bor $setUnderline))

$titleLabel1.Font = $newFont
$titleLabel2.Font = $newFont

Download the complete script here – FontDialog2.ps1

Advertisements