Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyHook doesn't detect key pressed in some windows

Tags:

python

pyhook

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?

like image 373
badprogrammerqq Avatar asked Oct 27 '15 20:10

badprogrammerqq


3 Answers

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.

like image 69
Abhishek Kashyap Avatar answered Oct 28 '22 06:10

Abhishek Kashyap


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.

like image 2
James Kent Avatar answered Oct 28 '22 06:10

James Kent


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()
like image 2
Dadu Khan Avatar answered Oct 28 '22 05:10

Dadu Khan