我有一个包含所有字母及其DirectInput密钥代码的2D数组:
string[,] DXKeyCodes = new string[,]
{
{"a","0x1E"},
{"b","0x30"},
...
};
然后,我有一个功能,可以根据字母从数组中返回十六进制密钥代码,如果我发送"'a'a it return'0x1e'。
然后,通过一个函数将此密钥代码作为击键发送到外部程序,该函数需要将密钥代码指定为简短,但我的数组包含字符串。
如何将此字符串转换为简短?
作为一个例子,这是有效的,但是当然,总是发送相同的关键代码:
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);
}
...
我确定有更好的方法,但找不到:(
感谢您的帮助。
itsme86和jasen在问题注释中,您应该使用 Dictionary<string, short>
而不是2D数组。这样,您可以通过其键查找值(而不是在要找到相应值时迭代数组搜索键(,而您不必从字符串中进行任何转换。例如,
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位。(
根据DirectInput文档,API具有Key
枚举。
所以,您可以这样填充您的字典:
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);