简体   繁体   English

如何更改RichTextBox中指定行的格式

[英]How to change the format of specified lines in a RichTextBox

I have a winforms RichTextBox containing lots of lines of text (eg 2 MB text files), and would like to programmatically change the formatting of specified lines, eg highlighting them. 我有一个winforms RichTextBox包含许多行文本(例如2 MB文本文件),并希望以编程方式更改指定行的格式,例如突出显示它们。

How can I address the lines, rather than the characters? 我该如何处理线条而不是字符? Is a RichTextBox even the best control for this sort of thing, or is there another alternative? RichTextBox甚至是对这类事情的最佳控制,还是有另一种选择? I have tried the Infragistics UltraFormattedTextEditor, but it was at least a couple of orders of magnitude slower to display text, so no good for my longer files. 我已经尝试过Infragistics UltraFormattedTextEditor,但显示文本的速度至少要低几个数量级,因此对于我的较长文件没有任何好处。

Thanks! 谢谢!

To access the lines on textbox controls you use the Lines property 要访问文本框控件上的行,请使用Lines属性

richTextBox.Lines richTextBox.Lines

From there you can iterate through the lines and work with the ones you want to change. 从那里你可以遍历这些线并使用你想要改变的线。

Edit: Agreed, I missed the highlight part (+1 for answering your own question). 编辑:同意,我错过了重点部分(+1回答你自己的问题)。 Including working code: 包括工作代码:

int lineCounter = 0;
foreach(string line in richTextBox1.Lines)
{
   //add conditional statement if not selecting all the lines
   richTextBox.Select(richTextBox.GetFirstCharIndexFromLine(lineCounter), line.Length);
   richTextBox.SelectionColor = Color.Red;
   lineCounter++;
}

OK, I'll document the solution I found: using richTextBox.Lines to get the lines as Luis says, then 好的,我将记录我找到的解决方案:使用richTextBox.Lines来获取Luis所说的那些行

richTextBox.GetFirstCharIndexFromLine(int line)
richTextBox.Select(int start, int length)

to select the relevant lines, then 然后选择相关的行

richTextBox.SelectionColor...
richTextBox.SelectionBackground...

etc. etc. to format the lines. 格式化线条等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM