Question

Python and SendKeys

import SendKeys, threading, pyHook, pythoncom
class Auto(threading.Thread):
    def run(self):
        SendKeys.SendKeys("{ENTER}",pause=0.1);
        print('Sent');
        exit();
def OnKeyboardEvent(event):
    if event.Ascii == 22:
        Auto().start();
    return True

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()

For some reason this program fails after running it exactly two times, I have no idea what the cause for this is. When you comment out the SendKeys part the program runs fine, so it has to be a problem with send keys.

[edit] Also, to clarify, running SendKeys.SendKeys(...) in a for i in range(0,100) works, so I assume it's something to do with the thread. I've never programmed threads before. Also this is just a mockup example to replicate the problem.

I'm running on windows 7, python2.6

[edit]Also, the program doesn't 'fail' it simply freezes (the function isn't run at all, it just sits there)

Was it helpful?

Solution

It seems that SendKeys is thread safe. The following code works on Vista - Python 2.6

class Auto(threading.Thread):
    def run(self):
        SendKeys.SendKeys("#",pause=0.1);
        print('Sent');
        exit();

for i in xrange(30):
    Auto().start()

Maybe the problem comes from some interferences with PyHook or the Windows PumpMessage mechanism. Have you tried to put the SendKeys part in a different process rather than in a different thread?

I hope it helps

OTHER TIPS

I am not so sure with the program but if you put exit(); in the middle of the program, It will quit program completely.

So Could you try without exit();?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top