我正在使用Windows表单,我有一个文本框,如果它是特定值,我想要偶尔将文本加粗。
我该如何在运行时更改字体特性?
我看到有一个名为textbox1.Font.Bold的属性,但这是只读属性。
字体本身的加粗属性是只读的,但文本框的实际字体属性并非如此。您可以按照以下方式将文本框的字体改为加粗:
textBox1.Font = new Font(textBox1.Font, FontStyle.Bold);
然后再返回:
textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);
根据您的应用程序,您可能希望在文本更改或焦点/取消焦点时使用该字体分配到相关的文本框。
以下是一个快速示例(空表单,只有一个文本框。当文本读取“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);
}
}
}
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();
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 );
}
txtText.Font = new Font("Segoe UI", 8,FontStyle.Bold);
//Font(Font Name,Font Size,Font.Style)