[英]How to select specific colored text in a RichTextBox control?
此函数将返回具有特定颜色的所有字符位置:
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;
但是当然可能有几个部分,您需要决定选择/突出显示哪个部分。 请注意,只有一个文本的部分可以选择/同时强调!
这是基本技术:
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
才能查看所选的文本。
richTextBox1.SelectTextByColor(Color.Blue);
richTextBox1.Focus();
如果您希望搜索从特定索引(例如文本的开头)而不是当前光标位置开始,则可以将该索引作为第二个参数传递给方法:
richTextBox1.SelectTextByColor(Color.Blue, 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.