如何在运行时将文本框的文本设置为粗体?

118

我正在使用Windows表单,我有一个文本框,如果它是特定值,我想要偶尔将文本加粗。

我该如何在运行时更改字体特性?

我看到有一个名为textbox1.Font.Bold的属性,但这是只读属性。

5个回答

222

字体本身的加粗属性是只读的,但文本框的实际字体属性并非如此。您可以按照以下方式将文本框的字体改为加粗:

  textBox1.Font = new Font(textBox1.Font, FontStyle.Bold);

然后再返回:

  textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);

1
哇,这比我想象的要容易得多。所以我猜这意味着字体就像字符串一样,一旦你创建了它,就不能更改它。你只能声明一个新实例。 - Diskdrive
2
是的,就其不可更改的状态而言,它似乎表现得像字符串一样,即它是不可变对象。然而,尽管有MSDN文章提到Font是不可变的,但Font本身的实际参考并没有说明这一点。 - Tim Lloyd
对于一个LinkButton,这个方法对我有效:button.Font.Bold = true。 - deebs
1
同样的事情可以针对部分文本完成吗?我的意思是我只想突出显示文本的一部分。 - Anil
@Anil - 为了回答这个问题并且为后人着想,是的。你可以将样式更改应用于选择字体,而不是一般的字体,方法如下:textBox1.SelectionFont = new Font(textBox1.Font, FontStyle.Bold);结合使用 AppendText 和随后的 FontStyle.Regular 更改(或者任何初始状态的样式),就可以实现你想要的效果。 - BJS3D

4

根据您的应用程序,您可能希望在文本更改或焦点/取消焦点时使用该字体分配到相关的文本框。

以下是一个快速示例(空表单,只有一个文本框。当文本读取“bold”(不区分大小写)时,字体变为粗体):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        RegisterEvents();
    }

    private void RegisterEvents()
    {
        _tboTest.TextChanged += new EventHandler(TboTest_TextChanged);
    }

    private void TboTest_TextChanged(object sender, EventArgs e)
    {
        // Change the text to bold on specified condition
        if (_tboTest.Text.Equals("Bold", StringComparison.OrdinalIgnoreCase))
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Bold);
        }
        else
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Regular);
        }
    }
}

2
你可以使用“扩展方法”来在“常规样式”和“粗体样式”之间进行切换,代码如下:
static class Helper
    {
        public static void SwtichToBoldRegular(this TextBox c)
        {
            if (c.Font.Style!= FontStyle.Bold)
                c.Font = new Font(c.Font, FontStyle.Bold);
            else
                c.Font = new Font(c.Font, FontStyle.Regular);
        }
    }

使用方法:

textBox1.SwtichToBoldRegular();

2
这里有一个例子可以切换加粗、下划线和斜体。
   protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
   {
      if ( ActiveControl is RichTextBox r )
      {
         if ( keyData == ( Keys.Control | Keys.B ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Bold ); // XOR will toggle
            return true;
         }
         if ( keyData == ( Keys.Control | Keys.U ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Underline ); // XOR will toggle
            return true;
         }
         if ( keyData == ( Keys.Control | Keys.I ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Italic ); // XOR will toggle
            return true;
         }
      }
      return base.ProcessCmdKey( ref msg, keyData );
   }

0
 txtText.Font = new Font("Segoe UI", 8,FontStyle.Bold);
 //Font(Font Name,Font Size,Font.Style)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接