将颜色更改为richtextbox中的选定文本时出现问题

时间:2014-02-20 21:17:01

标签: c# winforms richtextbox selection

我有这个代码,它已应用于表单。对于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;
                        }
                    }
                }
            }
        }
    }

问题是:

  1. 如果文件的第一个单词相同,则仅更改最后一个单词的颜色
  2. 如果最后一个单词错了,你输入的新文本将是红色的
  3. 如何强调Word中错误拼写错误的单词?
  4. 如果你能帮助我,我真的很感激!

1 个答案:

答案 0 :(得分:1)

这是一个工作示例,添加了单词的缓存,因此您不会每次都读取文件,修剪所有单词,将所有单词放在小写字母中并优化逻辑。我添加了注释,使代码易于阅读和理解。

WordList.txt包含

Apple 
Banana 
Computer

private void sottolinea_errori_Click(object sender, EventArgs e)
{
        // Get all the lines in the rich text box
        string[] textBoxLines = this.TextBox_stampa_contenuto.Lines;

        // Check that there is some text
        if (this.TextBox_stampa_contenuto.Text != string.Empty)
        {
            // Create a regular expression match
            Regex rgx = new Regex(@"\d");

            // Create a new dictionary to hold all the words
            Dictionary<string, int> wordDictionary = new Dictionary<string, int>();

            // Path to the list of words
            const string WordListPath = @"WordList.txt";

            // Open the file and read all the words
            StreamReader file = new StreamReader(WordListPath);

            // Read each file into the dictionary
            int i = 0;
            while (!file.EndOfStream)
            {
                // Read each word, one word per line
                string line = file.ReadLine();

                // Check if the line is empty or null and not in the dictionary
                if (!string.IsNullOrEmpty(line) && !wordDictionary.ContainsKey(line))
                {
                    // Add the word to the dictionary for easy lookup add the word to lower case
                    wordDictionary.Add(line.ToLower(), i);

                    // Incrament the counter
                    i++;
                }
            }

            // Close the file
            file.Close();

            // For each line in the text box loop over the logic
            foreach (string textLine in textBoxLines)
            {
                // Split the text line so we get individual words, remove empty entries and trim all the words
                string[] words = textLine.Split(new char[] { ' ', ',', '.', ':', '\t' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim().ToLower()).ToArray();

                // For each word that does not contain a digit
                foreach (string word in words.Where(x => !rgx.IsMatch(x)))
                {
                        // Check if the word is found, returns true if found
                        if (!wordDictionary.ContainsKey(word))
                        {
                            // Initialize the text modification variables
                            int wordStartPosition, seachIndex = 0;

                            // Find all instances of the current word
                            while ((wordStartPosition = this.TextBox_stampa_contenuto.Text.IndexOf(word, seachIndex, StringComparison.InvariantCultureIgnoreCase)) != -1)
                            {
                                // Select the word in the text box
                                this.TextBox_stampa_contenuto.Select(wordStartPosition, word.Length);

                                // Set the selection color
                                this.TextBox_stampa_contenuto.SelectionColor = Color.Red;

                                // Increase the search index after the word
                                seachIndex = wordStartPosition + word.Length;
                            }
                    }
                }
            }
        }
}