C# 将文本附加到富文本框中的开头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/850716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append text to the beginning in the Rich Text Box
提问by
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?
每次用户单击按钮时,我都希望新的“Enter”位于 RichTextBox 的顶部而不是底部。我该怎么做?
回答by Matt Hamilton
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:
您可以使用 SelectedText 属性在 RichTextBox 的开头插入文本。我刚刚敲了一个快速演示应用程序来测试它:
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.
当单击 button1 时,它会在 RichTextBox 的开头插入当前时间。
回答by Gaurav Gandhi
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.
它将在开始时添加 Current DateTime。
回答by Ahelyss
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);