【问题标题】:Problems changing color to a selected text in a richtextbox将颜色更改为富文本框中选定文本的问题
【发布时间】: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;
                        }
                    }
                }
            }
        }
    }

问题是:

  1. 如果文件的第一个单词相同,则仅更改最后一个单词的颜色
  2. 如果最后一个单词是错误的,那么您输入的新文本将是红色的
  3. 如何在 Word 中的拼写错误等错误单词下划线?

如果你能帮助我,我将不胜感激!

【问题讨论】:

  • 你能给出文件中的文本和文本框中的文本示例吗?您还可以在代码中添加一些 cmets,以便更容易理解,因为您的代码不是英文的。
  • 您没有在 while 循环中突出显示单词以使其变为红色。
  • 文件中的文本是28000个意大利语单词,每行一个。 Textbox中的文本是普通文本,就像一个txt文件,实际上这是一个文件编辑器的功能。
  • 那我该怎么办?抱歉,我正在学习 atm,所以我不是很专业。
  • 当您在 RichTextBox 中选择新文本时,它将不再突出显示之前选择的内容。因此,在您致电Select(indice, s.Length); 之后,您就有机会应用 SelectionColor。因此,将 SelectionColor 调用移到您的 while 循环中。

标签: c# winforms richtextbox selection


【解决方案1】:

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

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;
                            }
                    }
                }
            }
        }
}

【讨论】:

  • 您不需要 SelectionStart 和 SelectionLength 设置,您已经在循环开始时使用 Select 调用选择了文本。
  • @Marko 谢谢,太完美了!
猜你喜欢
  • 1970-01-01
  • 2013-08-03
  • 2017-07-24
  • 2011-08-10
  • 1970-01-01
  • 1970-01-01
  • 2010-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多