Remove FontStyle Bold from a Control's Font

ImGreg picture ImGreg · Mar 19, 2012 · Viewed 8.6k times · Source

I feel like a real noob posting this, but I can't seem to find anything for this...

I have a control that I'm basically trying to toggle the fontstyle between bold and not bold. This should be simple...

However, you can't acccess the Control.Font.Bold property as it is read only, therefore, you need to change the Font property.

To make it bold, I just do this:

this.btn_buttonBolding.Font = new Font(this.btn_buttonBolding.Font, FontStyle.Bold);

Not ideal, but it works. However, how do I go about removing this bold style (once it is bold already)?

I looked hard for duplicates; closest I could find was this, but it doesn't quite answer my situation: Substract Flag From FontStyle (Toggling FontStyles) [C#]

And this which gives how to set it, but not remove it: Change a font programmatically

Am I missing a simple constructor for the font that could do this? Or am I just missing something easier?

Answer

Ben Keene picture Ben Keene · Dec 17, 2013

I know this is a bit old, but I was faced with the exact same problem and came up with this:

Font opFont = this.btn_buttonBolding.Font;
if(value)
{
    this.btn_buttonBolding.Font = new Font(opFont, opFont.Style | FontStyle.Bold);
}
else 
{
    this.btn_buttonBolding.Font = new Font(opFont, opFont.Style & ~FontStyle.Bold);
}

The magic is in the "~" which is the bitwise NOT. (See the MSDN KB article "~Operator")