Steven Smethurst
Steven Smethurst

Reputation: 4614

Python crash with pyHook.HookManager() on KeyDown [ctrl]+[c]

I am creating a python script to record the keys that I press across my system (keylogger) and call home with information on what my typing habits are. I am new to python and I am using this application to learn about it. I am using python-3.x and windows 8

Full source code can be found here https://github.com/funvill/QSMonitor/blob/master/monitor.py

Using this snippet I am able to record all the keypress across my entire system. The problem is when I [ctrl]+[c] to copy something in another window the python code crashes.

Steps to reproduce

  1. Run the monitor.py script
  2. In another window (notepad.exe) type a few letters (abcd).
  3. Highlight the letters in notepad and hold down [ctrl] and press [c]

Experienced:

An windows error message would pop up and tell me that the python.exe has stop functioning and would need to be restarted. No python error message was in the command window.

def OnKeyboardEvent(event):
    global keyDatabase
    global keyLoggerCount 
    keyLoggerCount += 1 

    # http://code.activestate.com/recipes/553270-using-pyhook-to-block-windows-keys/ 
    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 ('---')    

    # check to see if this key has ever been pressed before 
    # if it has not then add it and set its start value to zero. 
    if event.Key not in keyDatabase:
        keyDatabase[ event.Key ] = 0 ; 

    # Incurment the key value 
    keyDatabase[ event.Key ] += 1 ; 
    return True

# When the user presses a key down anywhere on their system 
# the hook manager will call OnKeyboardEvent function.     
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()

while True : 
    pythoncom.PumpWaitingMessages()

My question is:

Upvotes: 0

Views: 2670

Answers (2)

If you want to catch KeyboardInterrupt exceptions, you could use a nested loop. This way when a KeyboardInterrupt occurs, the program exits only the inner loop.

while True:
    try:
        while True:
            pythoncom.PumpWaitingMessages()
    except KeyboardInterrupt:
        pass

Upvotes: 1

Patashu
Patashu

Reputation: 21773

In python, Ctrl+C throws a KeyboardInterrupt exception.

http://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt

Upvotes: 1

Related Questions