Detecting if a given font style exists in C#
Describes how to use the FontFamily object to determine if a given font style exists
In a previous article, Creating a WYSIWYG font ComboBox using C#, there is a hacky bit of code which uses a try catch block to handle processing when a given font style doesn't exist. This article describes a better way of handling this requirement without relying on the exception handler.
Originally we used the following code to determine if a font style exists: (Some of the additional code has been removed for clarity)
This code essentially "tests" each style by attempting to create a font instance of a given style. If the style doesn't exist, an exception is thrown and the code moves onto the next style.
A better way is to use the IsStyleAvailable
function of the
FontFamily
object. You simply create an instance of this
object with the name of the font you wish to query, then call
the method with the style to test. Note that the constructor for
FontFamily
will throw an exception if the font you try to
create doesn't exist.
Switching the GetFont method above to use IsStyleAvailable
ends up looking like this:
Based on this, a simple method to check if a given font name and
style exists is presented below. As the constructor for
FontFamily
throws an ArgumentException
if the given font
doesn't exist, we can trap that and return false
. Any other
error will be thrown, rather than being silently ignored as in
our earlier solution.
Like what you're reading? Perhaps you like to buy us a coffee?
# Jason
# Richard Moss
# yetaland
# Franc