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

1

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)
Bunde answered 16/11, 2010 at 20:6 Comment(1)
A similar approach to the solution for this also applies to TextBox controls. See my comment in the answer below.Kev
G
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);
}
Gustave answered 16/11, 2010 at 20:10 Comment(2)
Watchout ! If the current text selection has more than one font, SelectionFont will be null msdn.microsoft.com/query/…Finish
A similar approach also works with TextBox controls. The difference being that SelectionFont in the above example would need to be changed to Font.Kev

© 2022 - 2024 — McMap. All rights reserved.