如何将字符转换为密钥代码?

Mur*_*are 13 .net c#

如何将反斜杠键('\')转换为键代码?

在我的键盘上反斜杠代码是220,但方法如下

(int)'\\'
Run Code Online (Sandbox Code Playgroud)

让我回报92.

我需要一些通用的转换

 int ConvertCharToKeyValue(char c)
 {
     // some code here...
 }
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Han*_*ant 17

您可以P/Invoke VkKeyScan()将键入的密钥代码转换回虚拟密钥.请注意修改键的状态很重要,得到"|" 需要按住键盘布局上的shift键.你的功能签名不允许这样做,所以我做了一些事情:

    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);
Run Code Online (Sandbox Code Playgroud)

还要注意需要使用死键(Alt + Gr)生成输入键的键盘布局.这种代码最好避免使用.


Chr*_*lor 0

据我所知,没有一个函数可以将字符映射到虚拟键代码。但是,您可以使用下表开始构建此类映射。

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

请注意,您需要了解键盘,查看您提到的键“\”,这是 VK_OEM_5 虚拟键,对于美国键盘,如果不移动则为“\”,而“|” 如果转移,那么您的函数也需要知道正在使用的键盘。

当然,如果您想从虚拟键码映射到字符,您可以使用互操作来调用MapVirtualKeyEx函数。

更新根据您的评论,这将为您提供您想要的。

[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)'\\')
  {

  }
}
Run Code Online (Sandbox Code Playgroud)