如何将字符键code转换?如何将、字符、code

2023-09-03 05:01:57 作者:记得善良

我如何转换反斜线键('\')关键code?

How can I convert backslash key ('\') to key code?

在我的键盘反斜线code是220,但低于该方法

On my keyboard backslash code is 220, but the method below

(int)'\\'

返回我92。

returns me 92.

我需要一些像

 int ConvertCharToKeyValue(char c)
 {
     // some code here...
 }

任何想法?

推荐答案

您可以P / Invoke VkKeyScan()来转换一个打字键code回到一个虚拟键。要注意的是修改键的状态是很重要的,让|需要按住我的键盘布局Shift键。你的函数签名不允许这个,所以我只是做的东西了:

You can P/Invoke VkKeyScan() to convert a typing key code back to a virtual key. Beware that the modifier key state is important, getting "|" requires holding down the shift key on my keyboard layout. Your function signature doesn't allow for this so I just made something up:

    public static Keys ConvertCharToVirtualKey(char ch) {
        short vkey = VkKeyScan(ch);
        Keys retval = (Keys)(vkey & 0xff);
        int modifiers = vkey >> 8;
        if ((modifiers & 1) != 0) retval |= Keys.Shift;
        if ((modifiers & 2) != 0) retval |= Keys.Control;
        if ((modifiers & 4) != 0) retval |= Keys.Alt;
        return retval;
    }

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern short VkKeyScan(char ch);

另外要注意,需要使用死键(Alt + GR)来生成打字键的键盘布局。真的是最好避免这种code。

Also beware of keyboard layouts that need to use dead keys (Alt+Gr) to generate typing keys. This kind of code is really best avoided.