[英]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.