【问题标题】:Formatting first line of RichTextBox with capital letters and bold用大写字母和粗体格式化 RichTextBox 的第一行
【发布时间】:2017-01-02 22:28:02
【问题描述】:

如果我有一个 RichTextBox 并希望输出第一行是带有大写字母和粗体的字体,而下一行则相反,我该怎么办?

输出如下:

我的名字是
戴安娜
我的地址是
中国

【问题讨论】:

    标签: c# vb.net richtextbox


    【解决方案1】:

    嘿,试试这个,它有效,但如果用户输入速度非常快,例如按住“Enter”等,您可能会看到文本闪烁一秒钟。

        private void Form_Load(object sender, EventArgs e)
        {
            // append the function to the RichTextBox's TextChanged event
            MyRichTextBox.TextChanged += Capitalize_Bold_FirstLine;
        }
    
        private void Capitalize_Bold_FirstLine(object sender, EventArgs e)
        {
            RichTextBox box = sender as RichTextBox;
            if (box != null && box.Text != "")
            {
                // get the current selection text of the textbox
                int ss = box.SelectionStart;
                int sl = box.SelectionLength;
                // get the position where the first line ends
                int firstLineEnd = box.Text.IndexOf('\n');
                if (firstLineEnd < 0)
                    firstLineEnd = box.Text.Length;
    
                // split the lines
                string[] lines = box.Text.Split('\n');
                // capitalize the first line
                lines[0] = lines[0].ToUpper();
                // join them back and set the new text
                box.Text = String.Join("\n", lines);
                // select the first line and make it bold
                box.SelectionStart = 0;
                box.SelectionLength = firstLineEnd;
                box.SelectionFont = new Font(box.Font, FontStyle.Bold);
                // select the rest and make it regular
                box.SelectionStart = firstLineEnd;
                box.SelectionLength = box.Text.Length - firstLineEnd;
                box.SelectionFont = new Font(box.Font, FontStyle.Regular);
                // go back to what the user had selected
                box.SelectionStart = ss;
                box.SelectionLength = sl;
            }
        }
    

    【讨论】:

    • 谢谢您,您的程序运行正常,只有一行错误,然后我关闭错误,一直正常运行。错误的行是: // endof.Text = firstLineEnd.ToString();
    • @diana 没问题,是的,对不起,我用那行调试,一开始忘了把它拿出来,我在编辑我的帖子后把它拿出来了。
    猜你喜欢
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 2018-07-08
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多