Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Setting FontDialog to only display TrueType fonts

This question has been asked in practically every forum, including here but there are no acceptable answers anywhere that I can find. I'm beginning to think that there is actually no solution and I just have to wrap my code in a try/catch block and apologise to the user and ask them to pick another font.

I want to show a FontDialog so that a user can change the fonts on a Chart, however if the user selects a non-TrueType font, then an exception is thrown. GDI+ can only handle TrueType fonts.

How can I filter the fonts from the FontDialog which cannot be used with GDI+?

like image 389
Ozzah Avatar asked Jun 10 '11 05:06

Ozzah


2 Answers

The FontDialog class already does this, it uses the ChooseFont() API call with the CF_TTONLY option. Which forces the dialog to only display fonts that advertise themselves as TrueType fonts. The links suggests there are fonts around that fool the dialog, never heard of it before until today. Which makes it quite rare but certainly not unexpected, there are lots of junk fonts around with bad metadata.

There isn't anything you can do to catch the exception, it is raised in a callback function that's baked into the .NET framework. Rewriting the class is an option but not a pleasant one. Uninstalling the troublemaker font is certainly the easy solution.

like image 91
Hans Passant Avatar answered Oct 20 '22 01:10

Hans Passant


No real nice way around this one except to try/catch block it

try
{
    if (m_FontDialog.ShowDialog(frmMain.mainForm) == DialogResult.OK)
    {
        //Successful
    }
}
catch (Exception ex)
{
    //Not a truetype font
    MessageBox.Show(frmMain.mainForm, ex.Message + Environment.NewLine + "Font not changed.", "Font Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
like image 26
Astro29 Avatar answered Oct 19 '22 23:10

Astro29