Click here to Skip to main content
6,594,932 members and growing! (16,182 online)
Email Password   helpLost your password?
Desktop Development » Combo & List Boxes » Combo and List boxes     Intermediate License: The Code Project Open License (CPOL)

Managed Font Combobox

By Martin Cook

A managed combobox that displays a sample of each font in the system.
C#, Windows, .NET 1.1, GDI+, WinForms, VS.NET2003, Dev
Posted:4 Mar 2005
Views:92,936
Bookmarked:63 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
14 votes for this article.
Popularity: 4.98 Rating: 4.35 out of 5

1

2
3 votes, 21.4%
3
3 votes, 21.4%
4
8 votes, 57.1%
5

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


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.

Oh yea, and I also blog about writing C# code at CodeGator.com - come check it out!


Occupation: Web Developer
Location: United States United States

Other popular Combo & List Boxes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh)FirstPrevNext
GeneralDefault 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  
GeneralHow can I put the font listbox on the webpage? [modified] PinmemberJunior Boy18:44 6 Jun '07  
GeneralRe: How can I put the font listbox on the webpage? PinmemberMartin Cook4:12 8 Oct '07  
GeneralHow 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  
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  
GeneralDo you have a VB.NET version? Pinsussjouin@webfoxmail.com17:58 29 Apr '05  
GeneralRe: 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    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 4 Mar 2005
Editor: Smitha Vijayan
Copyright 2005 by Martin Cook
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project