[英]Mouse Recorder - how to detect mouse click in a while loop? with win32api
我想建立一个鼠标记录器,记录鼠标的动作和动作。
问题是我找不到使用win32api在while循环中检测鼠标按下的方法。
所以我试图使用两个线程来完成这项工作。
编辑-采取了一些不同的方法,将数据写入两个文件+现在,我需要以正确的顺序将其组合到一个文件中。
对我来说唯一剩下的问题是,是否有一种方法可以使用win32api在while循环中检测到鼠标单击? (所以我不需要使用另一个线程)
码:
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()
当首先更容易记录一个文件时,为什么要分离文件? 只需将来自不同线程的行放入队列中,然后将主线程中所述队列的内容写入文件中:
#!/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__()
和其他方法的类通常只是伪装为类的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.