I ran this PyHook sample code:
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()
To try it out and it works in most windows but when I try it inside a game window it acts like I'm not pressing anything.
Is there a way to listen to keypresses from a specific process? what should I do?
I am quoting from the same page from where you got this code. Check Here.
If you are using a GUI toolkit (e.g. wxPython), this loop is unnecessary since the toolkit provides its own.
I think you should change pythoncom.PumpMessages()
to something else I don't know what.
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.
Try using keyboard instead here is an example according to the keyboard page on Github. You have to run this with sudo
through the command (in command prompt) 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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With