我正在尝试在带有C#的windows7 x64上使用GetAsyncKeyState(i)来获取按键。它在x86上运行完美。这是我的代码:
[DllImport("user32.dll")]
public static extern int GetAsyncKeyState(long vKey);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
search = false;
int key_my;
for (i = 0; i < 255; i++)
{
key_my = GetAsyncKeyState(i); // this should return -3.... but it does 46...........
if ( key_my == (System.Int16.MinValue + 1))
{ search = true; break; }
}
if ( search == true)
{
...//using if to keys here.
}
任何IDEA?
答案 0 :(得分:5)
GetAsyncKeyState
函数的返回类型应为short
而不是int
,其参数应输入int
而不是long
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
答案 1 :(得分:0)
虽然这个问题已经得到了正确回答,但我想指出一下我使用这个答案的经验,并将它放在一行不工作。
if (GetAsyncKeyState(27) == (System.Int16.MinValue + 1))
不工作。
int key_my = GetAsyncKeyState(27);
if (key_my == (System.Int16.MinValue + 1))
工作。
(我不知道为什么。)