Search code examples
c#pinvokesendkeys

VkKeyScanEx/Sendinput alternative for unicode?


I'm currently trying to send a character. Therefore I use the native methods GetKeyboardLayout and VkKeyScanExW located in user32.dll to get the virtual key code (and shift- and control-state) for the current keyboard-layout from the system. Afterwards I send this virtual keycode to the application using the native method SendInput from user32.dll.

Everything work's fine - except of the euro sign. When I pass this character as parameter to VkKeyScanExW it returns -1, which means not found. On my Keyboard it is located using Ctrl+Menu+E (German layout)

Now I assume this occurs because the euro sign is a unicode sign and not mapped in the ascii-layout. I read Sendinput also allows a unicode-mode using a hardware scancode. So I hope using the unicode mode of SendInput will solve my problems. But I guess my virtualkey code is not the hardware scan code as unicode range is wider. Where can I find a sample how to send a unicode character (e.g. €) via SendInput to another control/window. MSDN and pinvoke.net do not provide useful samples.


Solution

  • In the meantime I solved the problem using the unicode parameter of SendInput. Now I don't have to use VkKeyScan any more - I can pass the character itself.

    private static void SendUnicodeChar(char input)
    {
        var inputStruct = new NativeWinApi.Input();
        inputStruct.type = NativeWinApi.INPUT_KEYBOARD;
        inputStruct.ki.wVk = 0;
        inputStruct.ki.wScan = input;
        inputStruct.ki.time = 0;
        var flags = NativeWinApi.KEYEVENTF_UNICODE;
        inputStruct.ki.dwFlags = flags;
        inputStruct.ki.dwExtraInfo = NativeWinApi.GetMessageExtraInfo();
    
        NativeWinApi.Input[] ip = { inputStruct };
        NativeWinApi.SendInput(1, ip, Marshal.SizeOf(inputStruct));
    }
    

    Thanks to all for the help.