【发布时间】:2021-10-03 13:28:29
【问题描述】:
下午好。我是作为海报堆栈溢出的新手,但多年来一直引用它。我已经研究了我的这个问题大约 2 周,虽然我已经看到了接近的解决方案,但我仍然遇到了一个问题。
我正在编写一个 C# gui,它读取一个汇编代码文件并突出显示不同的文本项,以便通过另一个程序进行进一步处理。我的表单有一个显示文本的 RichTextBox。在下面的情况下,我试图选择“;”位置处的文本,直到行尾并将文本更改为红色。这是我正在使用的代码。
请注意:程序读取的文件长度不一致,并非所有行的格式都相同,所以我不能简单地搜索';'并对其进行操作。
在另一篇文章中,一位成员给出了 AppendText 的扩展方法,除了原始文本和我重新格式化的文本仍然存在之外,我已经可以完美地工作了。这是该网站的链接: How to use multi color in richtextbox
// Loop that it all runs in
Foreach (var line in inArray)
{
// getting the index of the ‘;’ assembly comments
int cmntIndex = line.LastIndexOf(';');
// getting the index of where I am in the rtb at this time.
int rtbIndex = rtb.GetFirstCharIndexOfCurrentLine();
// just making sure I have a valid index
if (cmntIndex != -1)
{
// using rtb.select to only select the desired
// text but for some reason I get it all
rtb.Select(cmntIndex + rtbIndex, rtb.SelectionLength);
rtb.SelectionColor = Color.Red;
}
}
以下是原始文件中的示例汇编代码,所有文本均为黑色:
;;TAG SOMETHING, SOMEONE START
ASSEMBLY CODE ; Assembly comments
ASSEMBLY CODE ; Assembly comments
ASSEMBLY CODE ; Assembly comments
;;TAG SOMETHING, SOMEONE FINISH
当 rtb.GetFirstCharIndexOfCurrentLine() 被调用时,它返回一个有效的 RTB 索引,我想如果我添加 line.LastIndexOf(';') 返回的值,我将能够只选择上面看起来像 ; Assembly comments 的文本并转它是红色的。
实际情况是整条线都变红了。
当我使用上面的 AppendText 方法时,我得到了
ASSEMBLY CODE (this is black) ; Assembly comments (this is red) (the rest is black) ASSEMBLY CODE ; Assembly comments
黑色代码与重新着色的文本完全相同。在这种情况下,我需要知道如何清除 RTB 中的行和/或覆盖那里的文本。我尝试过的所有选项都会删除这些行。
任何人,我敢肯定这很长,但我真的很难过,非常感谢您的建议。
【问题讨论】:
标签: c# visual-studio-2010 foreach richtextbox appendtext