winforms 从OnKeyDown调用OnKeyPress

jucafojl  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(118)

由于某种原因在我的环境(CAD)按键没有被调用。2所以我需要手动调用它从overriding按键事件。3如何转换按键信息到字符传递到按键事件和正确管理有关修饰符,capslock,键盘布局,等所有情况?4有一个网络框架或低层次的窗口功能,为我做这件事吗?5谢谢

mf98qq94

mf98qq941#

我是这样解决的:

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int ToUnicode(
        uint virtualKeyCode,
        uint scanCode,
        byte[] keyboardState,
        StringBuilder receivingBuffer,
        int bufferSize,
        uint flags
    );

    [DllImport("user32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetKeyboardState(byte[] lpKeyState);

    string GetCharsFromKeys(Keys keys)
    {
        var buf = new StringBuilder(256);
        var keyboardState = new byte[256];
        
        GetKeyboardState(keyboardState);

        ToUnicode((uint)keys, 0, keyboardState, buf, 256, 0);
        return buf.ToString();
    }

    private void txt_KeyDown(object sender, KeyEventArgs e)
    {
        string text = GetCharsFromKeys(e.KeyData);
        if (!string.IsNullOrEmpty(text))
        {
            KeyPressEventArgs keyPressEventArgs = new KeyPressEventArgs(text[0]);
            OnKeyPress(keyPressEventArgs);
        }
    }

所有的键也使用修改键,capslock,alt gr等。

相关问题