10

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)
Jim Fell
  • 13,750
  • 36
  • 127
  • 202
Dada
  • 149
  • 3
  • 6
  • A similar approach to the solution for this also applies to `TextBox` controls. See my comment in the answer below. – Jim Fell May 20 '16 at 14:43

1 Answers1

12

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);
}
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • 4
    Watchout ! If the current text selection has more than one font, SelectionFont will be null http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.WINDOWS.FORMS.RICHTEXTBOX.SELECTIONFONT);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-VB)&rd=true – Matthieu Nov 02 '11 at 17:28
  • A similar approach also works with `TextBox` controls. The difference being that `SelectionFont` in the above example would need to be changed to `Font`. – Jim Fell May 20 '16 at 14:41