鼠标记录器 - 如何在while循环中检测鼠标单击?用win32api

时间:2016-10-12 13:48:20

标签: python multithreading python-2.7 python-3.x python-multithreading

我想构建一个记录鼠标动作和动作的鼠标记录器。

问题是我找不到用win32api在while循环中检测鼠标按下的方法。

所以我试图用两个线程来完成这项工作。

编辑 - 采用了一种不同的方法,将数据写入两个文件+时间 现在我需要将它组合成一个具有正确顺序的单个文件。

对我来说唯一的问题是,如果有办法检测 使用win32api在while循环中单击鼠标? (所以我不需要使用另一个线程)

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()

1 个答案:

答案 0 :(得分:0)

为什么在首先记录一个文件时更容易分隔文件?只需将来自不同线程的行放入队列,并将主线程中所述队列的内容写入文件:

#!/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()

如您所见,如果线程只有__init__()run()方法,则不需要为线程编写类。只有__init__()和另外一种方法的类通常只是伪装成类的函数。