Convert character to the corresponding virtual-key code

二次信任 提交于 2019-11-30 21:24:53

You should be clearer in what your requirements are, more specifically in what you consider to be an appropriate key code. The VkKeyScan as specified in it's documentation returns the virtual-key code in the low-order byte and the shift state in the high-byte of the return value.

This is demonstrated in the code snippet below that uses the '(' character as input for the VkKeyScan method.

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

static void Main(string[] args)
{
    var helper = new Helper { Value = VkKeyScan('(') };

    byte virtualKeyCode = helper.Low;
    byte shiftState = helper.High;

    Console.WriteLine("{0}|{1}", virtualKeyCode, (Keys)virtualKeyCode);
    Console.WriteLine("SHIFT pressed: {0}", (shiftState & 1) != 0);
    Console.WriteLine("CTRL pressed: {0}", (shiftState & 2) != 0);
    Console.WriteLine("ALT pressed: {0}", (shiftState & 4) != 0);
    Console.WriteLine();

    Keys key = (Keys)virtualKeyCode;

    key |= (shiftState & 1) != 0 ? Keys.Shift : Keys.None;
    key |= (shiftState & 2) != 0 ? Keys.Control : Keys.None;
    key |= (shiftState & 4) != 0 ? Keys.Alt : Keys.None;

    Console.WriteLine(key);
    Console.WriteLine(new KeysConverter().ConvertToString(key));
}

[StructLayout(LayoutKind.Explicit)]
struct Helper
{
    [FieldOffset(0)]public short Value;
    [FieldOffset(0)]public byte Low;
    [FieldOffset(1)]public byte High;
}

Running this snippet will result in the following output:

// 56|D8
// SHIFT pressed: True
// CTRL pressed: False
// ALT pressed: False
// 
// D8, Shift
// Shift+8
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!