首页 > 解决方案 > 键入时拼写检查器出现问题。如何仅更改部分文本的字体?

问题描述

当我使用 c# 在记事本应用程序中键入内容时,我尝试实现 Hunspell 拼写检查器库来检查我的拼写。它似乎工作正常,但是当出现拼写错误的单词时,整个 RichTextBox 都会被加下划线。

public void spellchecker()
{
    Invoke(new MethodInvoker(delegate ()
    {       
        using (Hunspell hunspell = new Hunspell("en_us.aff", "en_US.dic"))
        {
            String sentence = GetRichTextBox().Text;
            foreach (string item in sentence.Split(' '))
            {
                bool correct = hunspell.Spell(item);
                if (correct == false)

                {
                    GetRichTextBox().Font = new Font(GetRichTextBox().Font, FontStyle.Underline);
                }
                else {
                    GetRichTextBox().Font = new Font(GetRichTextBox().Font, FontStyle.Regular);
                }   

            }           
        }
    }));
}

错误似乎在该行中:

GetRichTextBox().Font = new Font(GetRichTextBox().Font, FontStyle.Underline);

因此,当我将其替换为:

item.Font = new Font(item.Font, FontStyle.Underline);

..出现一个错误,说“字符串不包含字体定义”。我无法将拼写错误的单词单独加下划线。

标签: c#.netwinformsrichtextbox

解决方案


首先,不要拆分字符串,' '因为这会将例如“Hello;world”视为一个单词。您应该使用 Regex 在字符串中查找单词。使用这种模式\w+

其次,如链接问题的这个答案所示,您可以在选择目标文本后SelectionColor使用和SelectionFont属性更改文本的样式。

这应该有效:

Font fnt = richTextBox1.Font;
Color color;

foreach (Match match in Regex.Matches(richTextBox1.Text, @"\w+"))
{
    string word = match.Value;
    if (!hunspell.Spell(word))
    {
        fnt = new Font(fnt.FontFamily, fnt.Size, FontStyle.Underline);
        color = Color.Red;
    }
    else
    {
        fnt = new Font(fnt.FontFamily, fnt.Size, FontStyle.Regular);
        color = Color.Black;
    }

    richTextBox1.Select(match.Index, match.Length);        // Selecting the matching word.
    richTextBox1.SelectionFont = fnt;                      // Changing its font and color
    richTextBox1.SelectionColor = color;
    richTextBox1.SelectionStart = richTextBox1.TextLength; // Resetting the selection.
    richTextBox1.SelectionLength = 0;
}

结果:

富文本框突出显示

注意:我用于if (word.length < 5)测试,您可以应用自己的条件,如上面的代码所示。

希望有帮助。


推荐阅读