在python中,在windows上,如何等到鼠标移动?

时间:2013-12-01 14:09:53

标签: python windows mouse

我正在开发一个屏幕捕获工具,这个工具旨在帮助软件开发人员了解用户最终如何崩溃应用程序。这个想法是在鼠标开始移动后开始捕获屏幕,并在5分钟后停止鼠标移动。通过使用ffmpeg的子进程,屏幕捕获工作正常,唯一剩下的问题(应用程序崩溃除外)是启动和停止屏幕捕获。我怎样才能做到这一点?理想情况下,它可以使用条件变量,但即使是一个测试鼠标是否在最后一秒移动的循环也可以。 python是否有可能支持OnMouseMove()

之类的东西

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

循环+ 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

答案 2 :(得分:1)

在考虑我的替代方案后,我认为这是处理我的问题的正确方法,请注意我已经通过检查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'