【问题标题】:Issue with Spell Checker as you type. How to Change font for only part of text?键入时拼写检查器出现问题。如何仅更改部分文本的字体?
【发布时间】:2018-05-11 12:36:32
【问题描述】:

我尝试实现 Hunspell 拼写检查器库,以便在我使用 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);

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

【问题讨论】:

  • GetRichTextBox().Font 改变整个 RichTextBox 的字体。 item.Font 无效,因为 item 只是一个没有 Font 属性的字符串。您的问题应该类似于 "How to change the font for only part of the text of RichTextBox".
  • 这是 WinForms 还是 WPF?
  • 这是一个 Windows 窗体应用程序
  • “不起作用”没有任何意义。编辑您的问题并在其他问题的帮助下显示您尝试过的内容以及您可能遇到的任何错误消息。

标签: c# .net winforms richtextbox


【解决方案1】:

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

其次,如this answer链接问题所示,选择目标文本后,可以使用SelectionColorSelectionFont属性更改文本样式

这应该可行:

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

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 2018-05-27
    • 2017-05-13
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多