c# - 键入时拼写检查器出现问题。如何仅更改部分文本的字体?
问题描述
当我使用 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);
..出现一个错误,说“字符串不包含字体定义”。我无法将拼写错误的单词单独加下划线。
解决方案
首先,不要拆分字符串,' '
因为这会将例如“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)
测试,您可以应用自己的条件,如上面的代码所示。
希望有帮助。
推荐阅读
- sql - PostgreSQL - 如何插入复合类型的数组
- java - Micronaut / Gradle / Kotlin 找不到 dll 文件
- android-studio - 身体单击时的单选按钮侦听器
- vba - MS Word 数量必须在 1 到 {n} 个 Cells.Split 行数之间 [错误 5148]
- python - ValueError:无法解释输入“State/UnionTerritory”
- android - 将数据从 ViewModel 发送到 ViewModel 并在 ViewPages 上显示
- javascript - AngularJS- TypeError: $element.find(...).each 不是函数
- html - 使用 justify-content: center 时列表被剪切
- vb.net - 快速 Ping 网络
- prolog - 学习Prolog:解决prolog中的填字游戏问题