在C#中更改字体?

Hun*_*ell 0 c# fonts winforms visual-c#-express-2010

我使用此代码使我的所有文本框都相同的字体:

          if (textBox1.Font.Underline)
        {
            foreach (Control y in this.Controls)
            {
                if (y is TextBox)
                {
                    ((TextBox)(y)).Font = new Font(((TextBox)(y)).Font, FontStyle.Regular);
                }
            }
        }
        else
        {
            foreach (Control y in this.Controls)
            {
                if (y is TextBox)
                {
                    ((TextBox)(y)).Font = new Font(((TextBox)(y)).Font, FontStyle.Underline);
                }
            }
Run Code Online (Sandbox Code Playgroud)

让我说我点击粗体按钮.该文将变为粗体.当我点击下划线按钮时,文字应该是粗体和下划线,但它只有下划线??? 为什么?

Mar*_*all 7

FontStyle是一个枚举,您可以将Or它们一起添加或Xor删除.

为现有样式添加下划线:

textBox1.Font = new Font(textBox1.Font, textBox1.Font.Style | FontStyle.Underline);
Run Code Online (Sandbox Code Playgroud)

从样式中删除下划线:

textBox1.Font = new Font(textBox1.Font, textBox1.Font.Style ^ FontStyle.Underline);
Run Code Online (Sandbox Code Playgroud)

并且您可以通过执行此操作来检查Font.Style中的Enumerations.

if ((textBox1.Font.Style.HasFlag(FontStyle.Underline)))
{
    textBox1.Font = new Font(textBox1.Font, textBox1.Font.Style ^ FontStyle.Underline);
}
else
{
    textBox1.Font = new Font(textBox1.Font, textBox1.Font.Style | FontStyle.Underline);
}
Run Code Online (Sandbox Code Playgroud)