There are 3 buttons: bold, italic and underline. Clicking on each of them changes the style of the text. I would like it to be like in a Word: pressing 1 time - a new style appeared, the second time on the same button - disappeared. So there was a problem: how to remove, say, bold type, so that everything else remains as well? I wrote:

if (textBox.Font.Bold) { textBox.Font = new Font(textBox.Font, textBox.Font.Style | FontStyle.Regular); } else { textBox.Font = new Font(textBox.Font, textBox.Font.Style | FontStyle.Bold); } 

I understand that FontStyle.Regular doesn’t fit, but I don’t know how to write differently, so I dropped it this way. Those. Specifically, in this situation, bold text is added normally, but then not removed.

  • FontStyle.Normal - Sergey Tambovites
  • why not use XOR to set / remove the flag? then even if is not needed. - rdorn
  • @rdorn, never worked with the ^ operator before. Now I read it on msdn, but I still don’t quite understand how to write it - Valeriy
  • one
    Just put ^ FontStyle.Bold in the first expression instead of | FontStyle.Regular | FontStyle.Regular . - Alexander Petrov
  • one
    added an answer, if something remains unclear, ask. In general, XOR is better to be friends with, sometimes it saves a lot of time =) - rdorn

1 answer 1

Use the bitwise ^ operation (XOR) to set and remove the necessary flags in the Font.Style property.

 textBox.Font = new Font(textBox.Font, textBox.Font.Style ^ FontStyle.Bold); 

Why this will work:

Suppose we have a set of flags A:10101010 and we need to change the value of 3 bits to the opposite. Then:

  A: 10101010 C: 10100010 xor xor B: 00001000 B: 00001000 = = C: 10100010 A: 10101010 

Thus, this operation allows you to invert the value of the flag without changing the values ​​of the other flags.

  • All figured out, thank you - Valeriy