C# 键入时出现拼写检查问题。如何仅更改部分文本的字体?

C# 键入时出现拼写检查问题。如何仅更改部分文本的字体?,c#,.net,winforms,richtextbox,C#,.net,Winforms,Richtextbox,我尝试实现拼写检查器库,在我使用c#输入记事本应用程序时检查拼写。它似乎可以正常工作,但当出现拼写错误的单词时,整个RichTextBox都会加下划线 public void spellchecker() { Invoke(new MethodInvoker(delegate () { using (Hunspell hunspell = new Hunspell("en_us.aff", "en_US.dic")) {

我尝试实现拼写检查器库,在我使用c#输入记事本应用程序时检查拼写。它似乎可以正常工作,但当出现拼写错误的单词时,整个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);

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

首先,不要将字符串按
''
拆分,因为这样会将“Hello;world”视为一个单词。您应该使用正则表达式在字符串中查找单词。使用此模式
\w+

其次,如链接问题的中所示,可以在选择目标文本后使用和属性更改文本样式

这应该起作用:

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)
进行测试,您可以应用您自己的条件,如上面的代码所示


希望有帮助。

GetRichTextBox()。Font
更改整个RichTextBox的字体<代码>项。Font无效,因为项只是一个没有
Font
属性的字符串。您的问题应该类似于“如何仅更改RichTextBox部分文本的字体”。这是WinForms还是WPF?这是Windows窗体应用程序可能重复的“不工作”没有任何意义。编辑您的问题,并显示您在其他问题的帮助下尝试了什么,以及可能出现的任何错误消息。