代码之家  ›  专栏  ›  技术社区  ›  Diskdrive

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

  •  85
  • Diskdrive  · 技术社区  · 16 年前

    我使用的是Windows窗体,我有一个文本框,如果它是某个值,我偶尔会想将文本加粗。

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

    4 回复  |  直到 16 年前
        1
  •  199
  •   Tim Lloyd    16 年前

    字体本身的粗体属性是只读的,但文本框的实际字体属性不是。您可以将文本框的字体更改为粗体,如下所示:

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

    然后又回来了:

      textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);
    
        2
  •  3
  •   Robert Hui    16 年前

    根据应用程序的不同,您可能希望在文本更改或文本框的焦点/非焦点时使用该字体指定。

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

    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);
            }
        }
    }
    
        3
  •  1
  •   Ali Hawk Rong    9 年前

    你可以用 Extension 切换方法 常规样式 大胆的风格 具体如下:

    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();
    
        4
  •  1
  •   Derek    6 年前

    下面是一个例子 切换 粗体、下划线和斜体。

       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 );
       }
    
        5
  •  0
  •   Joe Taras    8 年前
     txtText.Font = new Font("Segoe UI", 8,FontStyle.Bold);
     //Font(Font Name,Font Size,Font.Style)