14

我运行了这个 PyHook 示例代码:

    import pythoncom, pyHook

def OnKeyboardEvent(event):
    print 'MessageName:',event.MessageName
    print 'Message:',event.Message
    print 'Time:',event.Time
    print 'Window:',event.Window
    print 'WindowName:',event.WindowName
    print 'Ascii:', event.Ascii, chr(event.Ascii)
    print 'Key:', event.Key
    print 'KeyID:', event.KeyID
    print 'ScanCode:', event.ScanCode
    print 'Extended:', event.Extended
    print 'Injected:', event.Injected
    print 'Alt', event.Alt
    print 'Transition', event.Transition
    print '---'

# return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

尝试一下,它可以在大多数窗口中使用,但是当我在游戏窗口中尝试它时,它就像我没有按下任何东西一样。

有没有办法从特定进程中收听按键?我应该怎么办?

4

4 回答 4

2

Games often use hooks to handle input in much the same way as you are trying to, the way that hooks work under windows is as a chain, IIRC the last hook added is the first hook called, so it may be that if you are starting your script before the game then the games hook is called before yours, handles the event and so nothing reaches your hook.

Another possibility is that to prevent people for scripting/automating games or otherwise making things to help the player games will re-register the hooks periodically to ensure it is always at the head of the hook chain, if this is the case then you will find it difficult to overcome.

于 2019-05-29T10:03:42.820 回答
2

尝试使用键盘代替这里是根据 Github 上的键盘页面的示例。您必须sudo通过命令运行它(在命令提示符下)sudo python file.py

import sys
sys.path.append('..')
import keyboard
def print_pressed_keys(e):
    line = ', '.join(str(code) for code in keyboard._pressed_events)
    # '\r' and end='' overwrites the previous line.
    # ' '*40 prints 40 spaces at the end to ensure the previous line is cleared.
    print('\r' + line + ' ' * 40k, end='')


keyboard.hook(print_pressed_keys)
keyboard.wait()
于 2019-05-28T11:39:10.200 回答
2

我从您获得此代码的同一页面引用。 检查这里。

如果您使用的是 GUI 工具包(例如 wxPython),则该循环是不必要的,因为该工具包提供了自己的。

我想你应该换成pythoncom.PumpMessages()别的我不知道的东西。

于 2016-04-12T16:41:24.917 回答
1

您的问题可能是由于您的计算机将游戏优先于您的按键程序,所以当您按下一个键时,输入直接进入您的游戏而不是通过您的程序。

编辑:

实际上,有一种方法可以做到这一点。如果你按下ctrl+alt+del并选择task manager(windows),你应该能够看到你的 python 程序的名称。现在,右键单击它并选择Go to details. 这应该完全改变格式。无需单击其他任何内容,右键单击突出显示的内容(应以蓝色突出显示)并将鼠标悬停在Set priority. 这应该会弹出一个下拉菜单,您可以在其中设置为HighRealtime

确保执行此操作的另一种方法是将游戏的优先级设置为Below Normal使用相同的步骤,但改为单击游戏。

于 2019-05-29T00:14:25.070 回答