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

我使用 Windows 表单,我有一个文本框,我偶尔想使文本粗体,如果它是一定的值。

如何在运行时更改字体特征?

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

171708 次浏览

The bold property of the font itself is read only, but the actual font property of the text box is not. You can change the font of the textbox to bold as follows:

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

And then back again:

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

Depending on your application, you'll probably want to use that Font assignment either on text change or focus/unfocus of the textbox in question.

Here's a quick sample of what it could look like (empty form, with just a textbox. Font turns bold when the text reads 'bold', case-insensitive):

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);
}
}
}

You could use Extension method to switch between Regular Style and Bold Style as below:

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);
}
}

And usage:

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

Here is an example for toggling bold, underline, and italics.

   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 );
}