Search code examples
c#winformstextbox

How to know a textbox is Bold and Italic or not?


When a text is bold and italic. I was try to find out It is italic or not? But I failed.

if (txtText.Text.Font.Style == FontStyle.Italic)
        txtText.Font = new Font(txtText.Font, txtText.Font.Style ^ FontStyle.Italic);

. .

By this way,

 if (txtText.Text.Font.Style == FontStyle.Bold)
        txtText.Font = new Font(txtText.Font, txtText.Font.Style ^ FontStyle.Italic);

I only know the text is Bold or not.


Solution

  • You can't check equality like that to check if a particular bit is set.

    To check if the FontStyle.Italic bit is set, do:

    //True if italic is set
    if ((textText.Text.Font.Style & FontStyle.Italic) != 0)
    

    This works because every bit besides the one for FontStyle.Italic will be 0 in the result, and that bit will be 0 if it was 0 in the current style. Thus, if the current style has it set, the result will be non-zero, and zero if it isn't set.

    Also note that because you are using XOR below it, you will always just toggle the current setting of italic rather than set/unset it explicitly. Thus, your check may not even be necessary.