Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substract Flag From FontStyle (Toggling FontStyles) [C#]

I have a little problem. I have one 1 RichTextBox and 2 Buttons.

I have that 2 buttons for "toggle Bold FStyle" and "toggle Italic FStyle".

I want to toggle FontStyles without affecting other FontStyles. I hope you understand me.

Below code works when combining FontStyles but is not working when seperating/substracting FontStyles.

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font, (richTextBox1.SelectionFont.Bold == false ? richTextBox1.SelectionFont.Style | FontStyle.Bold : richTextBox1.SelectionFont.Style));
}

private void button2_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font, (richTextBox1.SelectionFont.Italic == false ? richTextBox1.SelectionFont.Style | FontStyle.Italic : richTextBox1.SelectionFont.Style));
}
  1. I make selected text Bold
  2. I make selected text Italic
  3. I want to remove Italic while Bold is still active (or opposite)
like image 677
Dada Avatar asked Nov 16 '10 20:11

Dada


1 Answers

The easiest way is to use bitwise XOR (^), which just toggles the value:

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font,
        richTextBox1.SelectionFont.Style ^ FontStyle.Bold);
}

private void button2_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font,
        richTextBox1.SelectionFont.Style ^ FontStyle.Italic);
}
like image 155
Heinzi Avatar answered Oct 07 '22 00:10

Heinzi