Click here to Skip to main content
Licence CPOL
First Posted 4 Mar 2005
Views 121,303
Downloads 1,285
Bookmarked 71 times

Managed Font Combobox

By Martin Cook | 4 Mar 2005
A managed combobox that displays a sample of each font in the system.

1

2
4 votes, 25.0%
3
3 votes, 18.8%
4
9 votes, 56.3%
5
4.31/5 - 16 votes
μ 4.32, σa 1.49 [?]

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:

  • The 'SelectedFontFamily' property, which is a runtime property for getting/setting the selected font in the combobox.
  • The 'SelectedIndex' property, which is a runtime property for getting/setting the selected index in the combobox.

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)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Martin Cook

Web Developer

United States United States

Member
I am a C# developer specializing in creating object-oriented software for Microsoft Windows. When I am not programming I enjoy reading, playing the guitar/piano, running, watching New York Ranger hockey, designing and building wacky electronic devices, and of course enjoying good times with my wife and children.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralGreat component! PinmemberSonOfGrey23:30 3 Mar '10  
GeneralRe: Great component! PinmemberStefan Strube9:10 7 Aug '11  
QuestionDefault font? PinmemberKevin Warner11:15 18 Apr '09  
GeneralProblem in VB .net Pinmemberagriweb9:25 23 Apr '08  
GeneralRe: Problem in VB .net PinmemberMartin Cook3:27 24 Apr '08  
QuestionFont ToolStripComboBox? PinmemberTim8w12:40 18 Apr '08  
GeneralRe: Font ToolStripComboBox? PinmemberMartin Cook3:39 24 Apr '08  
GeneralRe: Font ToolStripComboBox? [modified] Pinmemberhdr266:44 25 Nov '08  
QuestionHow can I put the font listbox on the webpage? [modified] PinmemberJunior Boy18:44 6 Jun '07  
AnswerRe: How can I put the font listbox on the webpage? PinmemberMartin Cook4:12 8 Oct '07  
QuestionHow to set the default font? Pinmemberdc19712:01 22 Aug '06  
AnswerRe: How to set the default font? PinmemberMartin Cook15:46 23 Aug '06  
QuestionRe: How to set the default font? PinmemberCongoFX8:58 14 Jun '07  
AnswerRe: How to set the default font? PinmemberMartin Cook6:12 15 Jun '07  
GeneralRe: How to set the default font? Pinmemberwmckenzie8:11 12 Jun '09  
Try - m_comboBox.SelectedItem = fontName
 
- where fontName is a string containing the FontFamily you want to set as the default
 
In VB.Net I used - Me.m_comboBox.SelectedItem = Me.Font.FontFamily.Name
to set the default value in the combo box to the form default
 

- great control, thanks Smile | :)
GeneralGreat control but small bug Pinmemberbren375:20 29 Jul '05  
GeneralRe: Great control but small bug PinmemberFonceur7:29 11 Aug '05  
GeneralRe: Great control but small bug Pinmemberdc19711:59 22 Aug '06  
QuestionDo you have a VB.NET version? Pinsussjouin@webfoxmail.com17:58 29 Apr '05  
AnswerRe: Do you have a VB.NET version? Pinmemberdc19711:59 22 Aug '06  
GeneralJust what i was looking for PinmemberPhilip Price1:50 5 Mar '05  
GeneralRe: Just what i was looking for PinmemberMartin Cook18:03 6 Mar '05  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120210.1 | Last Updated 4 Mar 2005
Article Copyright 2005 by Martin Cook
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid