Jul 05
Changing a font style is a bit easier than changing its size, as there is a Font constructor that accepts a font and style as arguments. For example, to bold a label’s font:
Label label = new Label(); . . . label.Font = new Font( label.Font, FontStyle.Bold );
If you want to keep the original style but also bold it:
label.Font = new Font( label.Font, label.Font.Style | FontStyle.Bold );
The problem with the approach above is that a new Font object is created whether it’s needed or not. Here is a handy method that will bold a font, creating a new Font object only if necessary:
static public Font BoldFont( Font font ) { if (font != null) { FontStyle fontStyle = font.Style; if ((fontStyle & FontStyle.Bold) == 0) { fontStyle |= FontStyle.Bold; font = new Font( font, fontStyle ); } } return font; }
For example, to bold a label’s font:
label.Font = BoldFont( label.Font );
Copyright © 2007-8 Tiwebb Ltd. All rights reserved. This material may not be published, broadcast, rewritten or redistributed without explicit permission from Tiwebb Ltd.


You code is correct in only case that all text is the same font name. I mean if your text mixes font(fontname),you coldn’t do like that. I have trouble to change fontstyle with the text that has one part in Times new roman and one part in Arial
THANK YOU!
A, BTW:
If you want to clear all styles fast use this method:
static public Font CleanFont(Font font)
{ if (font != null)
{ FontStyle fontStyle = font.Style;
fontStyle &= FontStyle.Bold;
fontStyle &= FontStyle.Italic;
fontStyle &= FontStyle.Strikeout;
fontStyle &= FontStyle.Underline;
font = new Font(font, fontStyle);
}
return font;
}
If my FontStyle is set to Bold AND Italic, then I set fontStyle &= FontStyle.Italic;
in order to keep activated just the Bold style, the system switch off all the styles so as a result the font is turned into Regular.
How can I switch off just a style (Bold, Italic or Underline) at a time?
Thanks!
C.
To clear a flag in an enumeration, you would use the following format:
fontStyle &= ~FontStyle.Italic;
Note the tilde ~ before FontStyle.Italic. This inverts the flag, then you are AND-ing it with the original fontStyle. This preserves all flags except FontStyle.Italic, which effectively “shuts off” the italic style.
Very helpful… Many thanks!