0

我为 Windows 编写了一个非常简单的工具来测量 Python 2.7 中两个事件之间的时间。具体来说:

  1. 用鼠标指向要作为参考的像素,然后按“左控制”键
  2. 当您想启动计时器时,您单击(任意位置)

代码如下:

import pyHook, pythoncom
import win32api
import sys
import time
from ctypes import windll
#from PIL import ImageGrab # alternative solution to windll

class Timer:
    def __init__ (self):
        pass

    def Reset (self):
        self.t = time.clock ()

    def Stop (self):
        self.t = time.clock () - self.t

    def Get (self):
        return self.t

def GetPixelColor (x, y):
    dc = windll.user32.GetDC (0)
    return windll.gdi32.GetPixel(dc, x, y)

class Test:
    def __init__ (self):
        self.timer = Timer ()
        self.color = -1
        self.ready = False

    def OnKbEvent (self, e):
        if e.Key == "Lcontrol":
            self.x, self.y = win32api.GetCursorPos ()
            self.color = GetPixelColor (self.x, self.y)
            self.ready = True
            print ("Control point selected")
            print (self.color)

        return True

    def OnMouseEvent(self, e):
        if self.ready:
            if e.Message == 513: # mouse left down
                self.timer.Reset ()
                while self.color == GetPixelColor (self.x, self.y):
                    time.sleep (0.100)
                self.timer.Stop ()
                print "%.5f" % self.timer.Get ()
                sys.exit ()

        return True

t = Test ()
hm = pyHook.HookManager ()
hm.KeyDown = t.OnKbEvent
hm.MouseAllButtonsDown = t.OnMouseEvent
hm.HookKeyboard ()
hm.HookMouse ()

pythoncom.PumpMessages ()

该脚本有效,但在我的机器(Win7)上比正常需要多 5 秒。在这段时间里,一切似乎都凝固了。

关于我做错了什么/如何改进脚本的任何提示?TIA

4

0 回答 0