Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove FontStyle Bold from a Control's Font

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?

like image 969
ImGreg Avatar asked Mar 19 '12 20:03

ImGreg


3 Answers

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")

like image 117
Ben Keene Avatar answered Sep 19 '22 16:09

Ben Keene


The FontStyle enum contains 5 distinct values. The one that reset your previous set is FontStyle.Regular

Regular Normal text.
Bold Bold text.
Italic Italic text.
Underline Underlined text.
Strikeout Text with a line through the middle.

It's a bitwise enum where Regular is 0. So setting this value alone reset all other flags

like image 26
Steve Avatar answered Sep 20 '22 16:09

Steve


Try this:

    private void btn_buttonBolding_Click(object sender, EventArgs e)
    {
        var style = btn_buttonBolding.Font.Bold ? FontStyle.Regular : FontStyle.Bold;
        btn_buttonBolding.Font = new Font(this.Font, style);
    }
like image 32
ionden Avatar answered Sep 19 '22 16:09

ionden