如何在Python中进行鼠标上/下/移动和按键事件

时间:2015-10-16 23:36:01

标签: python python-2.7 mouseevent keyboard-events pywin32

我在为Linux编写的Python 2.7项目上工作了一段时间,以便为它添加Windows支持。我正在试图弄清楚如何获得键盘按下和鼠标移动,按下或被释放的事件。我安装了win32api和pyHook,但我无法弄清楚如何正确使用它。请注意,我希望它能够获取事件,无论它在何处,而不仅仅是在命令提示符中按下它时。以下是如何在linux中执行此操作:

def handle_event(self):
    """ This function is called when a xlib event is fired """

    data = reply.data

    while len(data):
        event, data = rq.EventField(None).parse_binary_value(data, self._display.display, None, None)

        if event.type == X.MotionNotify:
            if self._mouse_last_x != None:
                mouse_distance=math.sqrt((event.root_x-self._mouse_last_x)**2+(event.root_y-self._mouse_last_y)**2)
                self.send_event(('mouse_moved',mouse_distance))
            self._mouse_last_x,self._mouse_last_y = event.root_x,event.root_y

        if event.type == X.ButtonPress:
            print event.sequence_number,event._data,event._fields
            self.send_event(('button_down',event._data['detail']))

        elif event.type == X.ButtonRelease:
            print event.sequence_number,event._data,event._fields
            self.send_event(('button_up',event._data['detail']))

        elif event.type == X.KeyPress and event.sequence_number == 0:
            key = event.detail
            self.send_event(('keys_pressed',key,1))

def run(self):
    self.disable_keyboard_interrupt()
    root = self._display.screen().root
    ctx = self._display.record_create_context(
                0,
                [record.AllClients],
                [{
                        'core_requests': (0, 0),
                        'core_replies': (0, 0),
                        'ext_requests': (0, 0, 0, 0),
                        'ext_replies': (0, 0, 0, 0),
                        'delivered_events': (0, 0),
                        'device_events': (X.KeyReleaseMask, X.PointerMotionMask),
                        'errors': (0, 0),
                        'client_started': False,
                        'client_died': False,
                }])

    self._display.record_enable_context(ctx, self.handle_event)

我似乎无法弄清楚如何在适用于任何库的Windows中使用它。

2 个答案:

答案 0 :(得分:0)

有Win32 API函数SetWindowsHookEx

Python上的示例:Applying low-level keyboard hooks with Python and SetWindowsHookExA

pyHook也是32位Python的好包(它有点过时了,你需要做一些努力,使用MinGW为x64重新构建它)。示例:Detecting Mouse clicks in windows using python

答案 1 :(得分:0)

要检测按下或释放的鼠标左键和右键,请在此处使用win32api检查我的解决方案: Python mouse click detection just with win32api