澄清:我想将文本行输出到RichTextBox中的相同“位置”,替换上一行。
在C#Windows窗体应用程序中尝试使用RichTextBox显示消息。大多数消息都是附加的,所以这很好,但是在程序的某个点上它有一个计数器,显示处理的行数。例如:
已处理:001记录。
等
嗯......我不需要用这样的数千行来填充RichTextBox:
已处理:001记录。
已处理:002 Recoeds。
相反,我试图将Caret移动到行的开头并再次写入行。可能需要删除RichTextBox中的上一行。无法弄清楚如何始终写入RichTextBox中相同的最后一行。
我尝试使用不起作用的SelectionStart和ScrollToCaret()。
答案 0 :(得分:1)
您可以尝试这样的事情(rtb是您的RichTextBox变量)
// Get the index of the last line in the richtextbox
int idx = rtb.Lines.Length - 1;
// Find the first char position of that line inside the text buffer
int first = rtb.GetFirstCharIndexFromLine(idx);
// Get the line length
int len = rtb.Lines[idx].Length;
// Select (Highlight) that text (from first to len chars)
rtb.SelectionStart = first;
rtb.SelectionLength = len;
// Replace that text with your update
rtb.SelectedText = "Processed: " + recordCount + " Records.";
未添加任何错误处理,但您可以添加一些检查以确保保留在文本缓冲区
中答案 1 :(得分:0)
一种解决方案是在开始处理之前存储当前文本:
string oldText = richTextBox.Text;
for (int i = 0; i < X; i++)
{
// process stuff
richTextBox.Text = oldText + Environment.NewLine + "Processed: " + i + " Records.";
}
我认为这种方法会忽略RTF数据,因此您可以使用RichTextBox.Rtf
代替。