在Python中,在Windows上,如何等待,直到鼠标移动?

我正在开发一个屏幕捕获工具,这个工具旨在帮助软件开发人员了解用户如何最终崩溃应用程序。 这个想法是一旦鼠标开始移动就开始屏幕捕捉,5分钟后鼠标停止移动。 屏幕捕获通过子过程与ffmpeg正常工作,唯一剩下的问题(应用程序崩溃除外)是启动和停止屏幕捕获。 我怎样才能做到这一点? 理想情况下,它可以与条件variables一起工作,甚至是一个testing鼠标是否在最后一秒移动的循环。 有什么机会python支持像OnMouseMove()

一个循环+ pywin32 ,像这样:

 import win32api from time import sleep count = 0 savedpos = win32api.GetCursorPos() while(True): if count>20*5: # break after 5sec break curpos = win32api.GetCursorPos() if savedpos != curpos: savedpos = curpos print "moved to " + str(savedpos) sleep(0.05) count +=1 

wxPython可以让你访问一整套你可以绑定的OnMouse事件。

考虑到我的替代方案,我认为这是正确的方式来处理我的问题,请注意我已经更新了代码,以支持远程桌面断开连接通过检查是否GetCursorPos()引发异常,也请注意当关闭远程桌面ffmpeg输出

[dshow @ ] real-time buffer full! frame dropped!

但输出文件看起来很好。 此脚本在Windows server 2012上进行了测试

 # http://ffmpeg.zeranoe.com/builds/ # http://www.videohelp.com/tools/UScreenCapture # http://sourceforge.net/projects/pywin32/files/pywin32/ import time, win32api, threading, subprocess, datetime, string, winerror StopRecordingTimeout = 10 def captureFunction(): pos = None proc = None counter = 0 while True: time.sleep(1) exceptFlag = False try: newPos = win32api.GetCursorPos() if pos == None: pos = newPos except Exception as e: if e[0] == winerror.ERROR_ACCESS_DENIED: exceptFlag = True if newPos != pos and proc != None: # mouse moved and we are recording already so just make sure the time out counter is zero counter = 0 elif newPos != pos and proc == None: # mouse moved and recording didn't start already fileName = filter(lambda x : x in string.digits, str(datetime.datetime.now())) fileName = 'output' + fileName + '.flv' print 'start recording to ' + fileName proc = subprocess.Popen('ffmpeg -f dshow -i video=UScreenCapture ' + fileName) elif proc != None and (newPos == pos or exceptFlag): # mouse didn't moved and recording already started if counter < StopRecordingTimeout and not exceptFlag: counter = counter + 1 print 'stop recording in ' + str(StopRecordingTimeout - counter) + ' seconds' elif exceptFlag or counter >= StopRecordingTimeout: print 'stop recording' proc.terminate() proc = None counter = 0 pos = newPos print 'start' captureThread = threading.Thread(target = captureFunction) captureThread.start() captureThread.join() print 'end'