代码之家  ›  专栏  ›  技术社区  ›  MadeByVince

DirectInput键代码-十六进制字符串变短

  •  -1
  • MadeByVince  · 技术社区  · 7 年前

    我有一个2D数组,包含所有字母及其DirectInput键代码:

    string[,] DXKeyCodes = new string[,]
    {
        {"a","0x1E"},
        {"b","0x30"},
        ...
    };
    

    然后我有一个函数,它从数组返回基于字母的十六进制代码,如果我发送“a”,它将返回“0x1E”。

    然后,该键代码通过一个函数作为击键发送到外部程序,该函数要求将键代码指定为short,但我的数组包含字符串。

    如何将这种字符串转换为短字符串?

    例如,这是可行的,但当然,总是发送相同的密钥代码:

    Send_Key(0x24, 0x0008);
    

    我需要这样的东西才能工作,这样我就可以发送任何给定的密钥代码:

    Send_Key(keycode, 0x0008);
    

    我尝试了以下方法,但也没有成功,只是让我的应用程序崩溃了。

    Send_Key(Convert.ToInt16(keycode), 0x0008);
    

    我真的不想去

    if (keycode == "a")
    {  
        Send_Key(0x1E, 0x0008);
    }
    else if (keycode == "b")
    {  
        Send_Key(0x30, 0x0008);
    }
    ...
    

    我相信有更好的方法,但我找不到:(

    谢谢你的帮助。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Joe Sewell    7 年前

    正如itsme86和Jasen在问题注释中提到的,您应该使用 a Dictionary<string, short> instead of a 2D array . 通过这种方式,您可以按键查找值(而不必在需要查找相应值时在数组中迭代搜索键),并且不必从字符串进行任何转换。例如。,

    Dictionary<string, short> DXKeyCodes = new Dictionary<string,short>
    {
      {"a", 0x1E},
      {"b", 0x30}
    };
    short theValue = DXKeyCodes["a"]; // don't need to loop over DXKeyCodes
                                      // don't need to convert from string
    

    如果出于任何原因必须将这些值存储为字符串,则使用静态方法 Convert.ToInt16(string, int) :

    short convertedValue = Convert.ToInt16("0x30", 16);
    

    (单位:C#, short 是的别名 System.Int16 并且始终有16位。)

        2
  •  1
  •   Stephen Kennedy annamataws    7 年前

    根据DirectInput文档,API具有 Key enumeration .

    因此,您可以填充 dictionary 这样地:

    var DXKeyCodes = new Dictionary<string,short>
    {
       { "a", (short)Microsoft.DirectX.DirectInput.Key.A }, // enum value of A is 30 which == 0x1E
       { "b", (short)Microsoft.DirectX.DirectInput.Key.B }
    };
    

    用法:

    Send_Key(DXKeyCodes[keycode], 0x0008);