Mouse Recorder - how to detect mouse click in a while loop? with win32api
<p>I want to build a mouse recorder that records the actions and movement the mouse makes.</p>

<p>the problem is i didn't find a way to detect a mouse press in a while loop with win32api.</p>

<p>So i am trying to use two threads to do the job.</p>

<hr>

<p><strong>EDIT- Taken a bit different approach , writing the data to two files + time
now i need to combine it into a single file with the right order.</strong></p>

<p><strong>The only question that remains for me is if there is a way to detect
a mouse click in a while loop with win32api?
(so i dont need to use another thread)</strong></p>

<p>CODE:</p>

<pre><code>import win32api, win32con
import time
import threading
from pynput.mouse import Listener
from datetime import datetime
import os
from pathlib import Path

clkFile = Path("clkTrk.txt")
posFile = Path('posTrk.txt')
if posFile.is_file():
os.remove('posTrk.txt')
if clkFile.is_file():
os.remove('clkTrk.txt')


class RecordClick(threading.Thread):

def __init__(self,TID,Name,Counter):
    threading.Thread.__init__(self)
    self.id = TID
    self.name = Name
    self.counter = Counter

def run(self):
    def on_click(x, y, button, pressed):
        if pressed: # Here put the code when the event occurres

            # Write Which button is clicked to the file
            button = str(button)
            file = open("clkTrk.txt", "at", encoding='UTF-8')
            file.write(str(datetime.now().second)+"-"+ button + "\n")
            print(button)
    with Listener(on_click=on_click, ) as listener:
        listener.join()


class RecordPos(threading.Thread):
def __init__(self,TID,Name,Counter):
    threading.Thread.__init__(self)
    self.id = TID
    self.name = Name
    self.counter = Counter

def run(self):
    file = open("posTrk.txt", "wt", encoding='UTF-8')
    while win32api.GetAsyncKeyState(win32con.VK_ESCAPE) != True:
        x = str(win32api.GetCursorPos()[0])
        y = str(win32api.GetCursorPos()[1])
        l = ",".join([x, y])
        print(l)
        file.write(str(datetime.now().second)+"-"+ l + "\n")
        time.sleep(0.2)


thread = RecordPos(1,"First",1)
thread2 = RecordClick(2,"Second",2)
thread.start()
thread2.start()
</code></pre>

<p>Why separate files when it is easier to record one file in the first place?  Just put the lines from the different threads into a queue and write the contents of said queue in the main thread into a file:</p>

<pre><code>#!/usr/bin/env python
# coding: utf8
from __future__ import absolute_import, division, print_function
import time
from functools import partial
from threading import Thread
from Queue import Queue
import win32api
import win32con
from pynput.mouse import Listener


def on_click(queue, x, y, button, pressed):
    if pressed:
        queue.put('{0},{1} {2}\n'.format(x, y, button))
        print(button)


def detect_clicks(queue):
    with Listener(on_click=partial(on_click, queue)) as listener:
        listener.join()


def track_movement(queue):
    while not win32api.GetAsyncKeyState(win32con.VK_ESCAPE):
        x, y = win32api.GetCursorPos()
        print(x, y)
        queue.put('{0},{1}\n'.format(x, y))
        time.sleep(0.2)


def main():
    queue = Queue()
    for function in [detect_clicks, track_movement]:
        thread = Thread(target=function, args=[queue])
        thread.daemon = True
        thread.start()
    with open('log.txt', 'w') as log_file:
        while True:
            log_file.write(queue.get())


if __name__ == '__main__':
    main()
</code></pre>

<p>As you see there is also not need to write classes for threads if those have just an <code>__init__()</code> and a <code>run()</code> method.  Classes with just an <code>__init__()</code> and one other method are often just functions disguised as classes.</p>

python multithreading python-2.7 python-3.x python-multithreading