我想在UWP中创建自定义的OnScreen键盘。它必须成为应用程序的一部分,因为它将用在大型桌子或木板设备上,因此完全控制键盘位置非常重要(桌子上的旋转)。

在WPF中,我已经通过创建带有Target属性的键盘控件来制作了这样的自定义键盘。当按下一个键时,它将使用UIElement.RaiseEvent(...)在目标上引发一个KeyEvent或TextComposition。
但是在UWP中,没有RaiseEvent函数,而且似乎没有办法为开发人员引发路由事件。

我想使用本机Text事件(KeyDown事件,TextComposition事件等),因此不能接受手动编辑TextBox(like this one)的Text属性的解决方案。

This page解释了如何创建一个侦听Text Services Framework的控件。我认为一种解决方案是创建自定义文本服务,但是我没有找到任何文档。

最佳答案

您可以使用Windows.UI.Input.Preview.Injection命名空间中的类以及受限制的inputInjectionBrokered功能来完成您正在寻找的部分内容。

这适用于KeyUpKeyDownPreviewKeyUpPreviewKeyDown事件,只要您不需要将击键发送到应用程序之外的任何内容即可。

非拉丁脚本不在我正在研究的范围之内,因此我不知道它是否可以扩展到将生成TextComposition事件的IME。

Martin Zikmund通过here上的示例解决方案演示了github的用法。

关键点是您需要编辑Package.appxmanifest文件(因为不是通过设计器进行编码),包括:

<Package>
    xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
    IgnorableNamespaces="rescap"
</Package>




<Capabilities>
    <rescap:Capability Name="inputInjectionBrokered" />
<Capabilities>


在这里,您可以通过以下方式模拟键入并引发本地键事件:

private async void TypeText()
{
    Input.Focus(FocusState.Programmatic);
    //we must yield the UI thread so that focus can be acquired
    await Task.Delay(100);

    InputInjector inputInjector = InputInjector.TryCreate();
    foreach (var letter in "hello")
    {
        var info = new InjectedInputKeyboardInfo();
        info.VirtualKey = (ushort)((VirtualKey)Enum.Parse(typeof(VirtualKey),
                                   letter.ToString(), true));
        inputInjector.InjectKeyboardInput(new[] { info });

        //and generate the key up event next, doing it this way avoids
        //the need for a delay like in Martin's sample code.
        info.KeyOptions = InjectedInputKeyOptions.KeyUp;
        inputInjector.InjectKeyboardInput(new[] { info });
    }
}

10-01 17:39
查看更多