RichTextbox 就地写入当前行
RichTextbox write in place to current line
澄清:我想将文本行输出到 RichTextBox 中的相同“位置”,以替换前一行。
在 C# 中 Windows 表单应用程序尝试使用 RichTextBox 来显示消息。大多数消息都是附加的,所以这很好,但在程序中的某一时刻它有一个计数器,显示已处理的行数。例如像这样:
Processed: 001 Records.
等等
好吧...我不需要它来像这样用数千行来填充 RichTextBox:
Processed: 001 Records.
Processed: 002 Recoeds.
相反,我试图将插入符号移动到行首并再次写入该行。可能需要删除 RichTextBox 中的上一行。无法弄清楚如何始终写入 RichTextBox 中的同一最后一行。
我尝试使用无效的 SelectionStart 和 ScrollToCaret()。
一种解决方案是在开始处理之前存储当前文本:
string oldText = richTextBox.Text;
for (int i = 0; i < X; i++)
{
// process stuff
richTextBox.Text = oldText + Environment.NewLine + "Processed: " + i + " Records.";
}
我认为此方法会忽略 RTF 数据,因此您可以改用 RichTextBox.Rtf
。
您可以尝试这样的操作(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.";
未添加错误处理,但您可以添加一些检查以确保保留在文本缓冲区内
澄清:我想将文本行输出到 RichTextBox 中的相同“位置”,以替换前一行。
在 C# 中 Windows 表单应用程序尝试使用 RichTextBox 来显示消息。大多数消息都是附加的,所以这很好,但在程序中的某一时刻它有一个计数器,显示已处理的行数。例如像这样:
Processed: 001 Records.
等等
好吧...我不需要它来像这样用数千行来填充 RichTextBox:
Processed: 001 Records.
Processed: 002 Recoeds.
相反,我试图将插入符号移动到行首并再次写入该行。可能需要删除 RichTextBox 中的上一行。无法弄清楚如何始终写入 RichTextBox 中的同一最后一行。
我尝试使用无效的 SelectionStart 和 ScrollToCaret()。
一种解决方案是在开始处理之前存储当前文本:
string oldText = richTextBox.Text;
for (int i = 0; i < X; i++)
{
// process stuff
richTextBox.Text = oldText + Environment.NewLine + "Processed: " + i + " Records.";
}
我认为此方法会忽略 RTF 数据,因此您可以改用 RichTextBox.Rtf
。
您可以尝试这样的操作(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.";
未添加错误处理,但您可以添加一些检查以确保保留在文本缓冲区内