Skip to main content
Email Password   helpLost your password?

Sample Image - CGFontCombo1.jpg

Introduction

I wrote this code one afternoon when I had some free time. I wanted to see how long it would take me to figure out how to enumerate through all the fonts in the system, then use those fonts to paint the associated entries in a combobox. Having finished the code, I decided the project might make for a good CodeProject article.

Using the code

For the most part, the control should be used like any other .NET custom control. The only thing to keep in mind is that I derived it from System.Windows.Forms.Control instead of System.Windows.Forms.ComboBox, so the properties and events will not be the same as a standard combobox. I made that decision because I felt that if I exposed the collection of combobox items, it would be too hard to manage the list of associated FontFamily objects. Honestly, I had visions of someone adding a non-existent font to the collection and leaving me to deal with the consequences - yuck. :o(

The only event is the 'SelectedIndexChanged' event, which is fired whenever a font name is selected in the combobox.

The only properties of any interest are:

To use the control in your code, just drop it on a form, wire up the SelectedIndexChanged event in the Visual Studio event designer, and add some code to respond to changes in the state of the control. Here is a demonstration of the SelectedIndexChanged handler from the sample application:

private void m_fontCombo_SelectedIndexChanged(object sender, System.EventArgs e)
{
    MessageBox.Show(
        this,
        "You selected: " + m_fontCombo.SelectedFontFamily.Name
        );
}

Points of Interest

There are two interesting internal parts to the control. The first is the code used to enumerate through the list of installed fonts:

private void CreateSampleFonts()
{

    // Should we simply exit?

    if (!IsHandleCreated || DesignMode)
        return;

    // Should we destroy any existing sample fonts?

    if (m_comboBox.Items.Count > 0)
    {

        // Loop and cleanup the fonts.

        for (int x = 0; x < m_comboBox.Items.Count; x++)
            ((Font)m_comboBox.Items[x]).Dispose();

        m_comboBox.Items.Clear();

    } // End if we should cleanup the sample fonts.


    // Gets the list of installed fonts.

    FontFamily[] ff = FontFamily.Families;

    // Loop and create a sample of each font.

    for (int x = 0; x < ff.Length; x++)
    {

        System.Drawing.Font font = null;

        // Create the font - based on the styles available.

        if (ff[x].IsStyleAvailable(FontStyle.Regular))
            font = new System.Drawing.Font(
                ff[x].Name, 
                m_comboBox.Font.Size
                );
        else if (ff[x].IsStyleAvailable(FontStyle.Bold))
            font = new System.Drawing.Font(
                ff[x].Name, 
                m_comboBox.Font.Size,
                FontStyle.Bold
                );
        else if (ff[x].IsStyleAvailable(FontStyle.Italic))
            font = new System.Drawing.Font(
                ff[x].Name, 
                m_comboBox.Font.Size,
                FontStyle.Italic
                );
        else if (ff[x].IsStyleAvailable(FontStyle.Strikeout))
            font = new System.Drawing.Font(
                ff[x].Name, 
                m_comboBox.Font.Size,
                FontStyle.Strikeout
                );
        else if (ff[x].IsStyleAvailable(FontStyle.Underline))
            font = new System.Drawing.Font(
                ff[x].Name, 
                m_comboBox.Font.Size,
                FontStyle.Underline
                );

        // Should we add the item?

        if (font != null)
            m_comboBox.Items.Add(font);

    } // End for all the fonts.


} // End CreateSampleFonts()

The FontFamily class makes the enumeration process trivial. Man I love C#! :o)

The second interesting part of the control is the code for actually painting the font entries:

private void m_comboBox_DrawItem(object sender, DrawItemEventArgs e)
{

    // If the index is invalid then simply exit.

    if (e.Index == -1 || e.Index >= m_comboBox.Items.Count)
        return;

    // Draw the background of the item.

    e.DrawBackground();

    // Should we draw the focus rectangle?

    if ((e.State & DrawItemState.Focus) != 0)
        e.DrawFocusRectangle();
    
    Brush b = null;
    
    try
    {

        // Create a new background brush.

        b = new SolidBrush(e.ForeColor);

        // Draw the item.

        e.Graphics.DrawString(
            ((Font)m_comboBox.Items[e.Index]).Name, 
            ((Font)m_comboBox.Items[e.Index]),
            b,
            e.Bounds
            );

    } // End try


    finally
    {

        // Should we cleanup the brush?

        if (b != null)
            b.Dispose();

        b = null;

    } // End finally


} // End m_comboBox_DrawItem()

All I really have to do is keep track of the item index and use that value to locate the proper FontFamily object. From there, it is simply a matter to draw the name of the font to the screen.

Conclusion

To be sure, there is a little more going on inside the control. However, most of it relates to forwarding events and properties to the embedded combobox control. Pretty boring stuff.

This code is new, and relatively untested. If you find bugs, just let me know and I'll do my best to squash them.

Have fun! :o)

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralDefault font? Pin
Kevin Warner
11:15 18 Apr '09  
GeneralProblem in VB .net Pin
agriweb
9:25 23 Apr '08  
GeneralRe: Problem in VB .net Pin
Martin Cook
3:27 24 Apr '08  
QuestionFont ToolStripComboBox? Pin
Tim8w
12:40 18 Apr '08  
GeneralRe: Font ToolStripComboBox? Pin
Martin Cook
3:39 24 Apr '08  
GeneralRe: Font ToolStripComboBox? [modified] Pin
hdr26
6:44 25 Nov '08  
GeneralHow can I put the font listbox on the webpage? [modified] Pin
Junior Boy
18:44 6 Jun '07  
GeneralRe: How can I put the font listbox on the webpage? Pin
Martin Cook
4:12 8 Oct '07  
GeneralHow to set the default font? Pin
dc197
12:01 22 Aug '06  
AnswerRe: How to set the default font? Pin
Martin Cook
15:46 23 Aug '06  
QuestionRe: How to set the default font? Pin
CongoFX
8:58 14 Jun '07  
AnswerRe: How to set the default font? Pin
Martin Cook
6:12 15 Jun '07  
GeneralRe: How to set the default font? Pin
wmckenzie
8:11 12 Jun '09  
GeneralGreat control but small bug Pin
bren37
5:20 29 Jul '05  
GeneralRe: Great control but small bug Pin
Fonceur
7:29 11 Aug '05  
GeneralRe: Great control but small bug Pin
dc197
11:59 22 Aug '06  
GeneralDo you have a VB.NET version? Pin
jouin@webfoxmail.com
17:58 29 Apr '05  
GeneralRe: Do you have a VB.NET version? Pin
dc197
11:59 22 Aug '06  
GeneralJust what i was looking for Pin
Philip Price
1:50 5 Mar '05  
GeneralRe: Just what i was looking for Pin
Martin Cook
18:03 6 Mar '05  


Last Updated 4 Mar 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2009