[英]How to color some words in differents lines in the RichTextBox?
我遇到了麻煩,今天我嘗試在單擊按鈕的不同行中為一些不同的單詞着色。 你能解釋一下如何做到這一點嗎? 我只能這樣做:
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的數量? 謝謝。
如果行以\\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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.