Python: How to start/stop while True loop on Keyboard event
<p>I am trying to write a little script that emulates mouse-clicking. It should start/stop when a combination of keys is pressed on the keyboard, so I figured every time this combination is pressed I would spawn or terminate a child process that just contains a while True loop and does some clicking. Now I can get the loop to start, but not to terminate. I tried creating a new process just for the HookManager, but i got the same results. Any help with this would be very appreciated</p>

<pre><code>import time
import win32api
import win32con
import pythoncom
import pyHook
import multiprocessing

i=0

def click():    
    while True:        
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
        time.sleep(0.005)


def OnKeyboardEvent(event):
    global i

    if (event.Ascii == 4) and (i == 0):
        i = 1
        c = multiprocessing.Process(target=click())
        c.start()
        print("started")

    elif (event.Ascii == 4) and (i == 1):
        i = 0
        c.terminate()
        print("terminated")

    return True


hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()       
pythoncom.PumpMessages()
</code></pre>