Append text to the beginning in the Rich Text Box

耗尽温柔 提交于 2019-12-04 02:57:50

问题


private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.AppendText("\r\n");
    richTextBox1.Focus();
    string s = "Enter ";
    richTextBox1.AppendText(s + "\r\n");
    richTextBox1.SelectionStart = richTextBox1.Text.Length - (s.Length +1);
    richTextBox1.SelectionLength = s.Length +1;
    richTextBox1.SelectionFont = new Font("Arial", 12, FontStyle.Bold);
    richTextBox1.DeselectAll();
    richTextBox1.SelectionStart = richTextBox1.Text.Length;
    richTextBox1.SelectionLength = richTextBox1.Text.Length;
    richTextBox1.SelectionFont = new Font("Arial", 12, FontStyle.Regular);
    richTextBox1.DeselectAll();
}

Every time a user clicks on the button I want that new "Enter" to be on the top not on the bottom of the RichTextBox. How can I do it?


回答1:


Technically if you're inserting it at the top of the text, you're "inserting" or "prepending", not "appending". ;)

You can use the SelectedText property to insert text at the start of a RichTextBox. I just knocked up a quick demo app to test it out:

    private void button1_Click(object sender, EventArgs e)
    {
        richTextBox1.SelectionStart = 0;
        richTextBox1.SelectionLength = 0;
        richTextBox1.SelectedText = DateTime.Now.ToString();
    }

That inserts the current time at the start of the RichTextBox when button1 is clicked.




回答2:


Simplest way i prefer is,

    private void button1_Click(object sender, EventArgs e)
    {
        richTextBox1.Text = DateTime.Now.ToString() + richTextBox1.Text;
    }

It will prepend Current DateTime at Start.




回答3:


previous messages seems obsolete. I solve it by :

Paragraph newExternalParagraph = new Paragraph();
newExternalParagraph.Inlines.Add( new Bold(new Run("[" + hour.ToString() + ":" + minute.ToString() + "]"))
{
    Foreground = Brushes.Yellow
});
_consoleText.Document.Blocks.InsertBefore(_consoleText.Document.Blocks.FirstBlock , newExternalParagraph);


来源:https://stackoverflow.com/questions/850716/append-text-to-the-beginning-in-the-rich-text-box

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!