答案 0 :(得分:1)
这是一个将返回具有特定颜色的所有角色位置的函数:
List<int> getColorPositions(RichTextBox rtb, Color col)
{
List<int> pos = new List<int>();
for (int i = 0; i < rtb.Text.Length; i++)
{
rtb.SelectionStart = i;
richTextBox1.SelectionLength = 1;
if (rtb.SelectionColor.ToArgb() == col.ToArgb() ) pos.Add(i);
}
return pos;
}
由你来挑选和选择你感兴趣的部分。
如果您确定只有一个部分具有您寻找的颜色,您可以选择以下部分:
rtb.SelectionStart = pos[0];
rtb.SelectionLength = pos.Count;
但当然可能有几个部分,您需要决定选择/突出显示哪个部分。请注意,一次只能选择/突出显示一个部分文字!
答案 1 :(得分:1)
这是基本技术:
RichTextBox
的文本并逐个选择每个字符。 SelectionColor
属性,以确定所选字符是否具有您要查找的颜色。 Select(firstIndex, secondIndex - firstIndex)
。您可以为RichTextBox
创建一个扩展方法,将上述内容封装成一个易于使用的方法:
public static class RichTextExtensions
{
/// <summary>
/// Searches for text in a RichTextBox control by color and selects it if found.
/// </summary>
/// <param name="rtb">The target RichTextBox.</param>
/// <param name="color">The color of text to search for.</param>
/// <param name="startIndex">The starting index to begin searching from (optional).
/// If this parameter is null, the search will begin at the point immediately
/// following the current selection or cursor position.</param>
/// <returns>If text of the specified color was found, the method returns the index
/// of the character following the selection; otherwise, -1 is returned.</returns>
public static int SelectTextByColor(this RichTextBox rtb, Color color, int? startIndex = null)
{
if (rtb == null || rtb.Text.Length == 0) return -1;
if (startIndex == null)
{
if (rtb.SelectionLength > 0)
startIndex = rtb.SelectionStart + rtb.SelectionLength;
else if (rtb.SelectionStart == rtb.Text.Length)
startIndex = 0;
else
startIndex = rtb.SelectionStart;
}
int matchStartIndex = rtb.FindTextByColor(color, startIndex.Value, true);
if (matchStartIndex == rtb.Text.Length)
{
rtb.Select(matchStartIndex, 0);
return -1;
}
int matchEndIndex = rtb.FindTextByColor(color, matchStartIndex, false);
rtb.Select(matchStartIndex, matchEndIndex - matchStartIndex);
return matchEndIndex;
}
private static int FindTextByColor(this RichTextBox rtb, Color color, int startIndex, bool match)
{
if (startIndex < 0) startIndex = 0;
for (int i = startIndex; i < rtb.Text.Length; i++)
{
rtb.Select(i, 1);
if ((match && rtb.SelectionColor == color) ||
(!match && rtb.SelectionColor != color))
return i;
}
return rtb.Text.Length;
}
}
您可以调用扩展方法,如下所示。请注意,如果您的RichTextBox
控件已启用HideSelection
(默认情况下会启用),则您需要将焦点设置回RichTextBox
才能看到所选文字。< / p>
richTextBox1.SelectTextByColor(Color.Blue);
richTextBox1.Focus();
如果希望搜索从特定索引(例如文本的开头)而不是当前光标位置开始,则可以将该索引作为第二个参数传递给方法:
richTextBox1.SelectTextByColor(Color.Blue, 0);