vb.net 如何使用 GetAsyncKeyState 实现全局热键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20045182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:52:12  来源:igfitidea点击:

How can I use GetAsyncKeyState to implement a global hotkey?

vb.netwinapi

提问by Jum Remdesk

I have created simple program that can capture key pressing globally on windows. i have used GetAsyncKeyState(). this is my code.

我创建了一个简单的程序,可以在 Windows 上全局捕获按键。我用过GetAsyncKeyState()。这是我的代码。

Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vkey As Integer) As Short

For i = 65 To 128
    If GetAsyncKeyState(i) = -32767 Then
        return Chr(i)
    End If
Next i

It works properly. but if i run another application used GetAsyncKeyState(), together my program (or two instance of my program) key capturing is does not work correctly. it capture some of keys, not all. for example; if I typed "stackoverflow" it capture "sakvrow"

它工作正常。但是如果我运行另一个使用的应用程序GetAsyncKeyState(),我的程序(或我的程序的两个实例)键捕获不能正常工作。它捕获了一些键,而不是全部。例如; 如果我输入“stackoverflow”,它会捕获“sakvrow”

where is the poblem and how can I fix it.

问题在哪里,我该如何解决。

采纳答案by manuell

Q: where is the poblem?

问:问题在哪里?

The problem is explained in the documentation:

文档中解释了该问题:

Although the least significant bit of the return value indicates whether the key has been pressed since the last query, due to the pre-emptive multitasking nature of Windows, another application can call GetAsyncKeyState and receive the "recently pressed" bit instead of your application. The behavior of the least significant bit of the return value is retained strictly for compatibility with 16-bit Windows applications (which are non-preemptive) and should not be relied upon.

尽管返回值的最低有效位指示自上次查询以来该键是否已被按下,但由于 Windows 的抢占式多任务特性,另一个应用程序可以调用 GetAsyncKeyState 并接收“最近按下”位而不是您的应用程序。为了与 16 位 Windows 应用程序(非抢占式)兼容,返回值的最低有效位的行为被严格保留,不应依赖

Q:how can I fix it?

问:我该如何解决?

As Hans suggested in comments, if you want some sort of "keylogger", you should use a keybord hook. See WH_KEYBOARD_LL

正如汉斯在评论中建议的那样,如果您想要某种“键盘记录器”,您应该使用键盘钩子。见WH_KEYBOARD_LL

回答by K3rnel31

put a textboxto see the events you have to add a timerset intervalto 100 enable it put this code on it

放一个textbox查看事件你必须添加一个timer设置interval为 100 启用它把这个代码放在上面

Dim result As Integer
    For i = 1 To 255
        result = 0
        result = GetAsyncKeyState(i)
        If result = -32767 Then
            TextBox1.Text = TextBox1.Text + Chr(i)
        End If
    Next i