Keyboard injection of symbols

ansalc 436 Reputation points
2020-05-21T16:45:34.907+00:00

How do I inject keyboard characters that are not alphabetical nor numerical, like the % or # ?

With the standard code below, or similar, I can inject alphabetical characters and numbers.

I have confirmed that info.ScanCode opens the possibility to inject other characters, but I can't find the way to map ScanCodes to Virtual Keys.

        foreach (char character in login0)
        {
            info.VirtualKey = (ushort)((VirtualKey)Enum.Parse(typeof(VirtualKey), character.ToString(), true));

            inputInjector.InjectKeyboardInput(new[] { info });
            await Task.Delay(40).ConfigureAwait(false);
        }
Universal Windows Platform (UWP)
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Richard Zhang-MSFT 6,936 Reputation points
    2020-05-22T05:25:44.607+00:00

    Hello,

    Welcome to Microsoft Q&A!

    Special characters cannot be directly mapped to a single VirtualKey. Taking "&" as an example, we use key combinations on most keyboards: Shift + 7. If you want to adapt to other characters, you need to write the key combination list yourself and match according to the input characters. This is a very tedious thing, and it is not universal.

    But triggered from the perspective of text input, each character corresponds to a unicode, we can accurately identify each character through Unicode, no longer need to consider the combination of VirtualKey mapping.

    In InputInjector, we can do this by setting KeyOptions:

    InputInjector inputInjector = InputInjector.TryCreate();
    foreach (var letter in "hello&yo")
    {
        var info = new InjectedInputKeyboardInfo();
        info.ScanCode = (ushort)letter;
        info.KeyOptions = InjectedInputKeyOptions.Unicode;
        inputInjector.InjectKeyboardInput(new[] { info });
        info.KeyOptions = InjectedInputKeyOptions.KeyUp;
        inputInjector.InjectKeyboardInput(new[] { info });
    }
    

    In the input text, we include the special characters &, but through Unicode, there is no difference between entering special characters and entering ordinary letters, because they all have exclusive Unicode.

    So this is a general method. You don't have to consider how to use VirtualKey for special characters, just use Unicode to recognize characters.

    Thanks.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.