How to convert a character to key code?

前端 未结 4 815
名媛妹妹
名媛妹妹 2020-12-11 01:35

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

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

(int)\'\\\\\'

ret

4条回答
  •  庸人自扰
    2020-12-11 02:13

    There is not a function that I know of that will map a character to a virtual key code. However, you can use the following table to start building such a mapping.

    http://msdn.microsoft.com/en-us/library/dd375731(v=VS.85).aspx.

    Note that you will need to know the keyboard, looking at the key you mention '\' this is the VK_OEM_5 virtual key which for US keyboards is '\' if not shifted and '|' if shifted, so your function will need to know the keyboard being used as well.

    Of course if you want to map from a virtual key code to a character you can use interop to call the MapVirtualKeyEx function.

    Update Based on your comment this would give you what you want.

    [DllImport("user32.dll")]
    static extern int MapVirtualKey(int uCode, uint uMapType);
    
    const uint MAPVK_VK_TO_CHAR = 0x02;
    
    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
      int key = MapVirtualKey((int)e.KeyCode, MAPVK_VK_TO_CHAR);
      if (key == (int)'\\')
      {
    
      }
    }
    

提交回复
热议问题