Friday, March 20, 2009

ComboBox set font style


Fill Combo with the available fonts in the system

public void fillFontCombo()
{
FontFamily[] families = FontFamily.Families;
//Loop Through System Fonts
foreach (FontFamily family in families)
{
//Set Current Font's Style To bold
FontStyle style = FontStyle.Bold;
//These Are Only Available In Italic, Not In "Regular",
//So Test For Them, Else, Exception!!
if (family.Name == "Monotype Corsiva" || family.Name == "Brush Script MT"
|| family.Name == "Harlow Solid Italic" || family.Name == "Palace Script MT" ||
family.Name == "Vivaldi")
{
//Set Style To Italic, To Overt "Regular" & Exception
style = style | FontStyle.Italic;
}
Font FCFont = new Font(family.Name, 10, style, GraphicsUnit.Point);
//Display The Font Combo Items
comboBox1.Items.Add(FCFont.Name);
}
comboBox1.SelectedIndex = 1;
}



Add drawitem eventhandler for the combobox to paint the combobox

private void combobox1_drawitem(object sender, DrawItemEventArgs e)
{
//If the index is invalid, do nothing and exit.
if (e.Index == -1 || e.Index >= comboBox1.Items.Count)
return;
//Draw the background of the item.
e.DrawBackground();
// Draw the focus rectangle
if ((e.State & DrawItemState.Focus) != 0)
e.DrawFocusRectangle();
Brush b = null;
try
{
// Create Background Brush.
b = new SolidBrush(e.ForeColor);
// Draw the item.
FontStyle style = FontStyle.Bold;
string strfont = comboBox1.Items[e.Index].ToString();
if (strfont == "Monotype Corsiva" || strfont == "Brush Script MT"
|| strfont == "Harlow Solid Italic" || strfont == "Palace Script MT"
|| strfont == "Vivaldi")
{
//Set Style To Italic, To Overt "Regular" & Exception
style = style | FontStyle.Italic | FontStyle.Regular;
}

Font nfont = new Font(strfont, 10, style);
e.Graphics.DrawString(
strfont,
nfont,
b,
e.Bounds
);

} // End try
finally
{
// Dispose the brush
if (b != null)
b.Dispose();
b = null;
} // End finally
}


Happy Coding :)

No comments:

Site Meter