【发布时间】:2014-03-22 02:29:02
【问题描述】:
我有此代码,它已应用于表单。对于richtextbox 中的每个单词,它会查看它是否存在于我用作字典的txt 文件中,如果不存在,则将该单词的颜色更改为红色。我知道代码会为每个单词打开和关闭流,我很快就会解决这个问题。
private void sottolinea_errori_Click(object sender, EventArgs e)
{
string line;
string[] linea = TextBox_stampa_contenuto.Lines;
if (TextBox_stampa_contenuto.Text != "")
{
foreach (string k in linea)
{
string[] parole = k.Split(new Char[] { ' ', ',', '.', ':', '\t' });
foreach (string s in parole)
{
Regex rgx = new Regex(@"\d");
if (!rgx.IsMatch(s))
{
if (s.Trim() != "")
{
s.Trim();
string path = @"280000parole.txt";
bool esito = true;
StreamReader file = new StreamReader(path);
while ((line = file.ReadLine()) != null && esito == true)
if (string.Compare(line, s) == 0)
esito = false; // i put this false when I find the word in the dictionary file
file.Close();
if (esito) //if true means that the word wasn't found
{
int inizioParola=0, indice; //indice means index, inizio parola is for selectionStart
while ((indice = TextBox_stampa_contenuto.Text.IndexOf(s, inizioParola)) != -1)
{
TextBox_stampa_contenuto.Select(indice, s.Length);
inizioParola = indice + s.Length;
}
TextBox_stampa_contenuto.SelectionStart = inizioParola - s.Length;
TextBox_stampa_contenuto.SelectionLength = s.Length;
TextBox_stampa_contenuto.SelectionColor = Color.Red;
}
TextBox_stampa_contenuto.SelectionLength = 0;
}
}
}
}
}
}
问题是:
- 如果文件的第一个单词相同,则仅更改最后一个单词的颜色
- 如果最后一个单词是错误的,那么您输入的新文本将是红色的
- 如何在 Word 中的拼写错误等错误单词下划线?
如果你能帮助我,我将不胜感激!
【问题讨论】:
-
你能给出文件中的文本和文本框中的文本示例吗?您还可以在代码中添加一些 cmets,以便更容易理解,因为您的代码不是英文的。
-
您没有在 while 循环中突出显示单词以使其变为红色。
-
文件中的文本是28000个意大利语单词,每行一个。 Textbox中的文本是普通文本,就像一个txt文件,实际上这是一个文件编辑器的功能。
-
那我该怎么办?抱歉,我正在学习 atm,所以我不是很专业。
-
当您在 RichTextBox 中选择新文本时,它将不再突出显示之前选择的内容。因此,在您致电
Select(indice, s.Length);之后,您就有机会应用 SelectionColor。因此,将 SelectionColor 调用移到您的 while 循环中。
标签: c# winforms richtextbox selection