You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WPF应用中调用Windows 10虚拟键盘自动补全API?

在WPF中获取Windows 10虚拟键盘的自动补全建议

可行方案

Windows 10虚拟键盘的自动补全功能基于系统文本预测框架,你可以通过WinRT API在WPF应用中直接获取这些建议,无需打开虚拟键盘,具体实现如下:

1. 引用WinRT组件

在WPF项目中添加对Windows.winmd的引用,路径通常为C:\Windows\System32\WinMetadata\Windows.winmd,确保项目目标框架为.NET Framework 4.6.2及以上,或.NET Core 3.0+。

2. 核心代码实现

利用Windows.UI.Text.Core命名空间下的CoreTextEditContext类监听文本预测请求,获取自动补全建议:

using Windows.UI.Text.Core;
using Windows.Globalization;
using System.Collections.ObjectModel;

public partial class MainWindow : Window
{
    private CoreTextEditContext _textEditContext;
    public ObservableCollection<string> SuggestionItems { get; set; } = new ObservableCollection<string>();

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        Loaded += Window_Loaded;
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // 获取当前视图的文本编辑上下文
        _textEditContext = CoreTextEditContext.GetForCurrentView();
        // 监听建议请求事件
        _textEditContext.SuggestionsRequested += OnSuggestionsRequested;
        // 设置目标语言(示例为法语)
        _textEditContext.InputLanguage = new Language("fr-FR");
    }

    private void OnSuggestionsRequested(CoreTextEditContext sender, CoreTextSuggestionsRequestedEventArgs args)
    {
        // 清空旧建议
        Dispatcher.Invoke(() => SuggestionItems.Clear());
        // 遍历获取到的预测建议
        foreach (var suggestion in args.Request.Suggestions)
        {
            Dispatcher.Invoke(() => SuggestionItems.Add(suggestion.Text));
        }
    }
}

3. 绑定到WPF界面

将建议集合绑定到下拉控件,比如ComboBox:

<ComboBox ItemsSource="{Binding SuggestionItems}" Width="200" Margin="10"/>

关键说明

  • 此方法依赖系统的文本预测功能,需确保系统设置中已开启(路径:设置→时间和语言→输入→高级键盘设置→语言栏选项→文本预测)。
  • WPF自带的拼写检查仅针对已输入完成的错误单词,确实不支持前缀补全和多词拆分修正(如cest→c'est、helloworld→hello world),而上述WinRT方案可直接复用系统虚拟键盘的预测逻辑,满足需求。

内容的提问来源于stack exchange,提问作者Gael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 00:01:06