Windows到CefSharp - 如何以正确的方式使用KeyEventArgs?

问题描述 投票:0回答:1

我点击输入字段登录我的帐户。问题是,现在我把所有字母都写成大写字母。在屏幕截图中,您可以看到输入字段是我输入“aaaa”但我得到“AAAA”。 enter image description here

1.Here ppl说KeyEvent无法处理小写,但我不知道我有什么替代方案。奇怪的是,在键盘上打字会创建小写字母。例如。按下键盘上的“7”将给我一个“g”。并且不建议使用字符串或字符,因为最后我需要一个整数/键。

这是我现在的路线:

        private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (!(Tag is TcpDeviceClient client)) return;
        if (e.Key == Key.Back) e.Handled = true;
        client?.SetKey(KeyInterop.VirtualKeyFromKey(e.Key), Keyboard.Modifiers.ToChromiumMods());

我插入了一个你可以在截图中看到的Console.WriteLine(这里缺少原因我想节省空间)。我每次打字时都会得到三种不同格式的密钥,这些格式与我的输入不符。请注意:在控制台中显示不同的字母。输入字段中显示的字母是正确的(但是以大写字母表示)。

我的问题如何以小写形式获得正确的按键?

wpf keyboard chromium cefsharp chromium-embedded
1个回答
0
投票

我为即将到来的访问者发布了同样问题的答案。我不得不提到这不是完美的答案/解决方案:

所以我仍然使用KeyEventArgs,获取密钥并将其发送到函数KeyCodeToUnicode()。但在此之前,你必须将WPF密钥转换为Win32虚拟密钥。

    private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (!(Tag is TcpDeviceClient client)) return;

        Char str = KeyCodeToUnicode((Key)KeyInterop.VirtualKeyFromKey(e.Key));
        Console.WriteLine("(int)e.Key: " + (int)e.Key + "\n VirtualKeyFromKey(e.Key): " + KeyInterop.VirtualKeyFromKey(e.Key) + "\n (Key)VirtualKeyFromKey(e.Key): " + (Key)KeyInterop.VirtualKeyFromKey(e.Key) + "\n KeyCodeToUnicode(e.Key)->str: " + str);
        Console.ReadLine();

        client?.SetKey(str, Keyboard.Modifiers.ToChromiumMods());
    }

在这里,我回来了。

    public Char KeyCodeToUnicode(Key key)
    {
        byte[] keyboardState = new byte[255];
        bool keyboardStateStatus = GetKeyboardState(keyboardState);

        if (!keyboardStateStatus)
        {
            return '\0';
        }

        uint virtualKeyCode = (uint)key;
        uint scanCode = (uint)MapVirtualKey(virtualKeyCode, 0);
        IntPtr inputLocaleIdentifier = GetKeyboardLayout(0);

        StringBuilder result = new StringBuilder();
        ToUnicodeEx(virtualKeyCode, scanCode, keyboardState, result, (int)5, (uint)0, inputLocaleIdentifier);

        if(result.ToString().Length < 1)
            return '\0';
        else
            return Convert.ToChar(result.ToString());
    }

在我的Input KeyCode()中,键再次被隐式转换为int。

    public void InputKeyCode(Char keycode, int modifier)
    {
        var host = Browser.GetBrowser().GetHost();

        KeyEvent kv = new KeyEvent();
        kv.WindowsKeyCode = keycode;
        //....
© www.soinside.com 2019 - 2024. All rights reserved.