拼写检查器

本文档介绍了如何使用所需词典配置拼写检查、从自定义词典中添加或删除单词、禁用拼写检查等。

默认情况下,拼写检查已启用并配置为使用 en-US 词典。 拼写检查器会检查已加载网页上的所有文本字段以及文本区域中的文本,并突出显示所有拼写错误的单词。 拼写检查器服务与配置文件相关联。 要访问和配置特定Profile的拼写检查器,请使用ISpellChecker接口:

ISpellChecker spellChecker = profile.SpellChecker;
Dim spellChecker As ISpellChecker = profile.SpellChecker

另一种选择是使用 Engine.Profiles.Default.SpellChecker 属性,该属性返回与默认配置文件关联的 ISpellChecker 服务实例。

添加语言

拼写检查器可以检查单个网页上不同语言的文本。 要配置所需的语言,请使用 spellChecker.Languages.Add() 方法。 Chromium 会自动从其网络服务器下载词典文件。

spellChecker.Languages.Add(Language.EnglishUs);
spellChecker.Languages.Add(Language.EnglishUs)

如果 Chromium 无法找到所需的词典,则会抛出 LanguageNotAvailableException(语言不可用异常)。

语言配置和词典存储在用户数据中。 如果将 IEngine 配置为使用特定的用户数据目录,它会记住语言设置并在下次恢复。

为了等待相应的语言从用户数据目录中加载,请使用以下代码:

spellChecker.Languages.Add(Language.EnglishUs).Wait();
spellChecker.Languages.Add(Language.EnglishUs).Wait()

删除语言

使用 spellChecker.Languages.Remove() 方法来停止对特定语言的拼写检查:

spellChecker.Languages.Remove(Language.EnglishUs);
spellChecker.Languages.Remove(Language.EnglishUs)

获取语言

要获取用于拼写检查的语言列表,请使用以下代码:

ISpellChecker spellChecker = Engine.Profiles.Default.SpellChecker;
IReadOnlyList<Language> languages = spellChecker.Languages.All;
Dim spellChecker As ISpellChecker = Engine.Profiles.Default.SpellChecker
Dim languages As IReadOnlyList(Of Language) = spellChecker.Languages.All

自定义词典

拼写检查程序支持自定义词典。 您可以使用 SpellChecker.CustomDictionary 属性访问自定义词典。

例如:

ISpellCheckDictionary dictionary = spellChecker.CustomDictionary;
Dim dictionary As ISpellCheckDictionary = spellChecker.CustomDictionary

添加单词

您可以使用 Add(string) 方法将单词添加到自定义词典中:

bool success = dictionary.Add("John");
Dim success As Boolean = dictionary.Add("John")

DotNetBrowser 对添加到自定义词典中的单词有以下要求: - UTF-8 编码的单词; - 单词长度在 1 到 99 个字节之间; - 没有前导和尾随的 ASCII 空白字符。

删除单词

要从自定义词典中删除单词,请使用 Remove(string) 方法,如以下代码示例所示:

bool success = dictionary.Remove("John");
Dim success As Boolean = dictionary.Remove("John")

禁用拼写检查

默认情况下,拼写检查是启用的。 您可以使用以下代码示例禁用它:

spellChecker.Enabled = false;
spellChecker.Enabled = False

上下文菜单

当用户右键单击加载网页上突出显示的拼写错误的单词时,可以显示带有建议的上下文菜单。 使用 IBrowser.ShowContextMenuHandler 来显示带有建议和将拼写错误的单词添加到自定义词典的上下文菜单。

WinForms

下面的代码示例演示了如何创建并显示带有建议和”Add to Dictionary“菜单项的 WinForms 上下文菜单。 使用此上下文菜单,您可以用其中一个建议替换拼写错误的单词,或将其添加到自定义词典中。

browser.ShowContextMenuHandler =
    new AsyncHandler<ShowContextMenuParameters,
        ShowContextMenuResponse>(ShowMenu);
browser.ShowContextMenuHandler =
     New AsyncHandler (Of ShowContextMenuParameters, ShowContextMenuResponse)(
         AddressOf ShowMenu)
private ToolStripItem BuildMenuItem(string item, bool isEnabled,
                                    EventHandler clickHandler)
{
    ToolStripItem result = new ToolStripMenuItem
    {
        Text = item,
        Enabled = isEnabled
    };
    result.Click += clickHandler;

    return result;
}

private Task<ShowContextMenuResponse> ShowMenu(ShowContextMenuParameters parameters)
{
    TaskCompletionSource<ShowContextMenuResponse> tcs =
        new TaskCompletionSource<ShowContextMenuResponse>();

    SpellCheckMenu spellCheckMenu = parameters.SpellCheckMenu;
    if (spellCheckMenu != null)
    {
        BeginInvoke(new Action(() =>
        {
            ContextMenuStrip popupMenu = new ContextMenuStrip();
            IEnumerable<string> suggestions = spellCheckMenu.DictionarySuggestions;
            if (suggestions != null)
            {
                // 添加带有建议的菜单项。
                foreach (string suggestion in suggestions)
                {
                    popupMenu.Items.Add(BuildMenuItem(suggestion, true, delegate
                    {
                        browser.ReplaceMisspelledWord(suggestion);
                        tcs.TrySetResult(ShowContextMenuResponse.Close());
                    }));
                }
            }

        // 添加"Add to Dictionary"菜单项。
            string addToDictionary =
                spellCheckMenu.AddToDictionaryMenuItemText ?? "Add to Dictionary";

            popupMenu.Items.Add(BuildMenuItem(addToDictionary, true, delegate
            {
                if (!string.IsNullOrWhiteSpace(spellCheckMenu.MisspelledWord))
                {
                    engine.Profiles.Default.SpellChecker?.CustomDictionary
                         ?.Add(spellCheckMenu.MisspelledWord);
                }

                tcs.TrySetResult(ShowContextMenuResponse.Close());
            }));

            // 当浏览器请求焦点返回时关闭上下文菜单。
            EventHandler<FocusRequestedEventArgs> onFocusRequested = null;
            onFocusRequested = (sender, args) =>
            {
                BeginInvoke((Action) (() => popupMenu.Close()));
                parameters.Browser.FocusRequested -= onFocusRequested;
            };
            parameters.Browser.FocusRequested += onFocusRequested;

            // 处理菜单关闭事件。
            ToolStripDropDownClosedEventHandler menuOnClosed = null;
            menuOnClosed = (sender, args) =>
            {
                bool itemNotClicked =
                    args.CloseReason != ToolStripDropDownCloseReason.ItemClicked;
                if (itemNotClicked)
                {
                    tcs.TrySetResult(ShowContextMenuResponse.Close());
                }

                popupMenu.Closed -= menuOnClosed;
            };
            popupMenu.Closed += menuOnClosed;

            // 显示上下文菜单。
            Point location = new Point(parameters.Location.X, parameters.Location.Y);
            popupMenu.Show(this, location);
            tcs.TrySetResult(ShowContextMenuResponse.Close());
        }));
    }
    else
    {
        tcs.TrySetResult(ShowContextMenuResponse.Close());
    }

    return tcs.Task;
}
Private Function BuildMenuItem(item As String, isEnabled As Boolean,
                               clickHandler As EventHandler) As ToolStripItem
    Dim result As ToolStripItem = New ToolStripMenuItem With {
        .Text = item,
        .Enabled = isEnabled
    }
    AddHandler result.Click, clickHandler

    Return result
End Function

Private Function ShowMenu(parameters As ShowContextMenuParameters) _
    As Task(Of ShowContextMenuResponse)

    Dim tcs As New TaskCompletionSource(Of ShowContextMenuResponse)()
    Dim spellCheckMenu As SpellCheckMenu = parameters.SpellCheckMenu
    If spellCheckMenu IsNot Nothing Then
        BeginInvoke(New Action(Sub()
            Dim popupMenu As New ContextMenuStrip()
            Dim suggestions As IEnumerable(Of String) =
                    spellCheckMenu.DictionarySuggestions

            If suggestions IsNot Nothing Then
                ' 添加带有建议的菜单项。
                For Each suggestion As String In suggestions
                    popupMenu.Items.Add(BuildMenuItem(suggestion, True, Sub()
                        browser.ReplaceMisspelledWord(suggestion)
                        tcs.TrySetResult(ShowContextMenuResponse.Close())
                    End Sub))
                Next suggestion
            End If

            ' 添加"Add to Dictionary"菜单项。
            Dim addToDictionary As String =
                If (spellCheckMenu.AddToDictionaryMenuItemText, "Add to Dictionary")

            popupMenu.Items.Add(BuildMenuItem(addToDictionary, True, Sub()
                If Not String.IsNullOrWhiteSpace(spellCheckMenu.MisspelledWord) Then
                    engine.Profiles.Default.SpellChecker?.CustomDictionary? .Add(
                        spellCheckMenu.MisspelledWord)
                End If
                tcs.TrySetResult(ShowContextMenuResponse.Close())
            End Sub))

            ' 当浏览器请求焦点返回时关闭上下文菜单。
            Dim onFocusRequested As EventHandler(Of FocusRequestedEventArgs) = Nothing
            onFocusRequested = Sub(sender, args)
                BeginInvoke(CType(Sub() popupMenu.Close(), Action))
                RemoveHandler parameters.Browser.FocusRequested, onFocusRequested
            End Sub
            AddHandler parameters.Browser.FocusRequested, onFocusRequested

            ' 处理菜单关闭事件。
            Dim menuOnClosed As ToolStripDropDownClosedEventHandler = Nothing
            menuOnClosed = Sub(sender, args)
                Dim itemNotClicked As Boolean = args.CloseReason <>
                                                ToolStripDropDownCloseReason.ItemClicked

                If itemNotClicked Then
                    tcs.TrySetResult(ShowContextMenuResponse.Close())
                End If

                RemoveHandler popupMenu.Closed, menuOnClosed
            End Sub
            AddHandler popupMenu.Closed, menuOnClosed

            ' 显示上下文菜单。
            Dim location As New Point(parameters.Location.X, parameters.Location.Y)
            popupMenu.Show(Me, location)
            tcs.TrySetResult(ShowContextMenuResponse.Close())
        End Sub))
    Else
        tcs.TrySetResult(ShowContextMenuResponse.Close())
    End If
    Return tcs.Task
End Function

如果右键单击拼写错误的单词,则会出现上下文菜单:

WinForms 拼写检查器上下文菜单

我们的存储库中提供了完整的示例: C#, VB.NET.

WPF

下面的代码示例演示了如何创建和显示带有建议和 Add to Dictionary 菜单项的 WPF 上下文菜单。 使用此上下文菜单,您可以用其中一个建议替换拼写错误的单词,或将其添加到自定义词典中。

browser.ShowContextMenuHandler =
    new AsyncHandler<ShowContextMenuParameters, 
                     ShowContextMenuResponse>(ShowContextMenu);
browser.ShowContextMenuHandler =
    New AsyncHandler(Of ShowContextMenuParameters, ShowContextMenuResponse)(
        AddressOf ShowContextMenu)
private Task<ShowContextMenuResponse> ShowContextMenu(
    ShowContextMenuParameters parameters)
{
    TaskCompletionSource<ShowContextMenuResponse> tcs =
        new TaskCompletionSource<ShowContextMenuResponse>();

    SpellCheckMenu spellCheckMenu = parameters.SpellCheckMenu;
    WebView.Dispatcher?.BeginInvoke(new Action(() =>
    {
        System.Windows.Controls.ContextMenu popupMenu =
            new System.Windows.Controls.ContextMenu();

        IEnumerable<string> suggestions = spellCheckMenu.DictionarySuggestions;
        if (suggestions != null)
        {
            // 添加带有建议的菜单项。
            foreach (string suggestion in suggestions)
            {
                MenuItem menuItem =
                    BuildMenuItem(suggestion, true,
                                  delegate
                                  {
                                      browser.ReplaceMisspelledWord(suggestion);
                                      tcs.TrySetResult(ShowContextMenuResponse
                                                          .Close());
                                  });
                popupMenu.Items.Add(menuItem);
            }
        }

        // 添加 "Add to Dictionary" 菜单项。
        string addToDictionary =
            spellCheckMenu.AddToDictionaryMenuItemText ?? "Add to Dictionary";

        popupMenu.Items.Add(BuildMenuItem(addToDictionary, true, delegate
        {
            if (!string.IsNullOrWhiteSpace(spellCheckMenu.MisspelledWord))
            {
                engine.Profiles.Default.SpellChecker?.CustomDictionary
                     ?.Add(spellCheckMenu.MisspelledWord);
            }

            tcs.TrySetResult(ShowContextMenuResponse.Close());
        }));

        popupMenu.Closed += (sender, args) =>
        {
            tcs.TrySetResult(ShowContextMenuResponse.Close());
        };

        popupMenu.IsOpen = true;
    }));
    return tcs.Task;
}
Private Function ShowContextMenu(parameters As ShowContextMenuParameters) _
    As Task(Of ShowContextMenuResponse)

    Dim tcs As New TaskCompletionSource(Of ShowContextMenuResponse)()
    Dim spellCheckMenu As SpellCheckMenu = parameters.SpellCheckMenu
    WebView.Dispatcher?.BeginInvoke(New Action(Sub()
        Dim popupMenu As New Controls.ContextMenu()

        Dim suggestions As IEnumerable(Of String) = spellCheckMenu.DictionarySuggestions
        If suggestions IsNot Nothing Then
            ' 添加带有建议的菜单项
            For Each suggestion As String In suggestions
                Dim menuItem As MenuItem = BuildMenuItem(suggestion, True, Sub()
                    browser.ReplaceMisspelledWord(suggestion)
                    tcs.TrySetResult(ShowContextMenuResponse.Close())
                End Sub)
                popupMenu.Items.Add(menuItem)
            Next suggestion
        End If

        ' 添加 "Add to Dictionary" 菜单项。
        Dim addToDictionary As String =
                If(spellCheckMenu.AddToDictionaryMenuItemText, "Add to Dictionary")

        popupMenu.Items.Add(BuildMenuItem(addToDictionary, True, Sub()
            If Not String.IsNullOrWhiteSpace(spellCheckMenu.MisspelledWord) Then
                engine.Profiles.Default.SpellChecker?.CustomDictionary?.Add(
                    spellCheckMenu.MisspelledWord)
            End If

            tcs.TrySetResult(ShowContextMenuResponse.Close())
        End Sub))
        AddHandler popupMenu.Closed, Sub(sender, args)
            tcs.TrySetResult(ShowContextMenuResponse.Close())
        End Sub

        popupMenu.IsOpen = True
    End Sub))
    Return tcs.Task
End Function

如果右键单击拼写错误的单词,则会出现上下文菜单: WPF 拼写检查器上下文菜单

Avalonia UI

下面的代码示例演示了如何创建和显示带有建议和 Add to Dictionary 菜单项的 Avalonia UI 上下文菜单。 使用此上下文菜单,您可以用其中一个建议替换拼写错误的单词,或将其添加到自定义词典中。

browser.ShowContextMenuHandler =
    new AsyncHandler<ShowContextMenuParameters,
        ShowContextMenuResponse>(ShowContextMenu);
private Task<ShowContextMenuResponse> ShowContextMenu(
    ShowContextMenuParameters parameters)
{
    TaskCompletionSource<ShowContextMenuResponse> tcs =
        new TaskCompletionSource<ShowContextMenuResponse>();

    SpellCheckMenu spellCheckMenu = parameters.SpellCheckMenu;
    Dispatcher.UIThread.InvokeAsync(() =>
    {
        Avalonia.Controls.ContextMenu? cm = new();
        cm.Placement = PlacementMode.Pointer;
        Point point = new Point(parameters.Location.X, parameters.Location.Y);
        cm.PlacementRect = new Rect(point, new Size(1, 1));

        IEnumerable<string> suggestions = spellCheckMenu.DictionarySuggestions;
        if (suggestions != null)
        {
            // 添加带有建议的菜单项
            foreach (string suggestion in suggestions)
            {
                MenuItem menuItem =
                    BuildMenuItem(suggestion, true, true,
                                  delegate
                                  {
                                      browser.ReplaceMisspelledWord(suggestion);
                                      tcs.TrySetResult(ShowContextMenuResponse
                                         .Close());
                                  });
                cm.Items.Add(menuItem);
            }
        }

        // 添加 "Add to Dictionary" 菜单项.
        string addToDictionary =
            spellCheckMenu.AddToDictionaryMenuItemText ?? "Add to Dictionary";

        cm.Items.Add(BuildMenuItem(addToDictionary, true, true, delegate
        {
            if (!string.IsNullOrWhiteSpace(spellCheckMenu.MisspelledWord))
            {
                engine.Profiles.Default.SpellChecker?.CustomDictionary
                     ?.Add(spellCheckMenu.MisspelledWord);
            }

            tcs.TrySetResult(ShowContextMenuResponse.Close());
        }));

        cm.Closed += (s, a) => tcs.TrySetResult(ShowContextMenuResponse.Close());
        cm.Open(BrowserView);
    });
    return tcs.Task;
}

如果右键单击拼写错误的单词,则会出现上下文菜单: Avalonia 拼写检查器上下文菜单

拼写检查事件

当加载的网页上的文本字段或文本区域处于焦点时,拼写检查器会自动检查文本并突出显示拼写错误的单词。 要在文本检查完成后获取通知,请使用 IBrowser.SpellCheckCompleted 事件,如下代码示例所示:

browser.SpellCheckCompleted += (s, e) => 
{
    // 已检查的文本。
    string text = e.CheckedText;
    // 拼写检查结果列表。
    foreach(SpellCheckingResult spellCheckingResult in e.Results)
    {
        // 被检查文本中
        // 拼写错误单词的第一个符号的位置,
        // 被拼写检查器标记为拼写错误。
        uint location = spellCheckingResult.Location;
        // 检查文本中拼写错误单词的长度。
        uint length = spellCheckingResult.Length;
    }
};
AddHandler browser.SpellCheckCompleted, Sub(s, e)
    ' 已检查的文本。
    Dim text As String = e.CheckedText
    ' 拼写检查结果列表。
    For Each spellCheckingResult As SpellCheckingResult In e.Results
        ' 被检查文本中
        ' 拼写错误单词的第一个符号的位置,
        ' 被拼写检查器标记为拼写错误。
        Dim location As UInteger = spellCheckingResult.Location
        ' 检查文本中拼写错误单词的长度。
        Dim length As UInteger = spellCheckingResult.Length
    Next
End Sub
Go Top