Search code examples
c#uwpkeyboard

UWP - InjectedInputKeyboardInfo how to send non-English keystrokes


I have a UWP app in Visual Studio 2017. I'm trying to make a multi-language on-screen keyboard. Currently the English keystrokes are working fine, however any letter from other languages throws System.ArgumentException: 'Value does not fall within the expected range.'

Here is the code that sends the keystrokes:

public void SendKey(ushort keyCode)
{
    List<InjectedInputKeyboardInfo> inputs = new List<InjectedInputKeyboardInfo>();
    InjectedInputKeyboardInfo myinput = new InjectedInputKeyboardInfo();

    myinput.VirtualKey = keyCode;

    inputs.Add(myinput);
    var injector = InputInjector.TryCreate();

    WebViewDemo.Focus(FocusState.Keyboard);
    injector.InjectKeyboardInput(inputs); // exception throws here
}

How would I inject letters from other languages?


Solution

  • The trick is that InputInjector isn't injecting text (characters), but actually it is injecting key strokes on the keyboard. That means the input will be not what the VirtualKey value contains as the name value, but what the given key represents on the keyboard the user is currently using.

    For example in Czech language we use the top numeric row to write characters like "ě", "š" and so on. So when you press number 3 on the keyboard, Czech keyboard writes "š".

    If I use your code with Number3 value:

    SendKey( (ushort)VirtualKey.Number3 );
    

    I get "š" as the output. The same thing holds for Japanese for example where VirtualKey.A will actually map to ”あ”.

    That makes InputInjector for keyboard a bit inconvenient to use, because you cannot predict which language the user is actually using a which keyboard key mapping is taking place, but after reflection it makes sense it is implemented this way, because it is not injection of text, but simulation of actual keyboard keystrokes.