我遇到了麻烦,今天我尝试在单击按钮的不同行中为一些不同的单词着色。你能解释一下如何做到这一点吗?我只能做到这一点:
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Select(int start , int length); //It's wrong but It explains How to use .Select if you know start and length...
richTextBox1.SelectionColor = Color.Blue;
}
但是我怎么能在一条线上工作我知道已经将文本放入RichTextBox的数量? 感谢。
答案 0 :(得分:2)
如果行被\n
分隔,则问题是在到达所需行之前计算\n
个字符的数量。
为此,您可以使用扩展方法:
public static int NthIndexOf(this String str, String match, int occurence) {
int i = 1;
int index = 0;
while (i <= occurence && ( index = str.IndexOf(match, index + 1) ) != -1) {
if (i == occurence) {
// Occurence match found!
return index;
}
i++;
}
// Match not found
return -1;
}
现在,您可以找到start
和end
值来为选择设置颜色:
private void button1_Click(object sender, EventArgs e) {
int lineNb = 13; // I assume you get this value initialized somewhere,
// I wrote 13 for the example
int start = richTextBox1.Text.NthIndexOf("\n", lineNb);
int length = richTextBox1.Text.NthIndexOf("\n", lineNb + 1);
richTextBox1.Select(start , length);
richTextBox1.SelectionColor = Color.Blue;
}