Python脚本不响应鼠标事件

2024-04-25 21:51:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,用于侦听鼠标单击全局事件:

from AppKit import *
from PyObjCTools import AppHelper
import CoreFoundation

def handler(event):
    NSLog(event)
    print(event)

NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSLeftMouseDownMask, handler)
AppHelper.runConsoleEventLoop()

但是,这只是永远运行,不响应鼠标事件,有什么问题吗


Tags: fromimport脚本eventdef事件鼠标全局
1条回答
网友
1楼 · 发布于 2024-04-25 21:51:14

有两件事不对:

  • 您需要首先创建一个应用程序实例,然后将事件处理程序附加到它
  • 您需要使用^{}来检测鼠标点击

PyObjCTools API docs提供了许多示例代码。您可以查看HelloWorld脚本以了解如何创建应用程序对象。您需要将调用addGlobalMonitorForEventsMatchingMask_handler_的原始代码放在applicationDidFinishLaunching回调中

from AppKit import *
from PyObjCTools import AppHelper
import CoreFoundation

class AppDelegate(NSObject):
    def applicationDidFinishLaunching_(self, notification):
        NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSLeftMouseDownMask, handler)

def handler(event):
    NSLog(u"%@", event)
    print(event)

if __name__ == '__main__':
    app = NSApplication.sharedApplication()

    # we must keep a reference to the delegate object ourselves,
    # NSApp.setDelegate_() doesn't retain it. A local variable is
    # enough here.
    delegate = AppDelegate.alloc().init()
    NSApp().setDelegate_(delegate)

    AppHelper.runEventLoop()

我使用的是macOS 10.13.6和Python3.7,我通过鼠标左键点击得到:

2019-08-17 12:10:57.071 python[16084:78526] NSEvent: type=LMouseDown loc=(1034,130) time=13052.3 flags=0 win=0x0 winNum=131 ctxt=0x0 evNum=0 click=1 buttonNumber=0 pressure=1 deviceID:0x0 subtype=0
NSEvent: type=LMouseDown loc=(1034,130) time=13052.3 flags=0 win=0x0 winNum=131 ctxt=0x0 evNum=0 click=1 buttonNumber=0 pressure=1 deviceID:0x0 subtype=0
2019-08-17 12:10:57.323 python[16084:78526] NSEvent: type=LMouseDown loc=(890,99) time=13052.5 flags=0 win=0x0 winNum=131 ctxt=0x0 evNum=0 click=1 buttonNumber=0 pressure=1 deviceID:0x0 subtype=0
NSEvent: type=LMouseDown loc=(890,99) time=13052.5 flags=0 win=0x0 winNum=131 ctxt=0x0 evNum=0 click=1 buttonNumber=0 pressure=1 deviceID:0x0 subtype=0
2019-08-17 12:10:57.452 python[16084:78526] NSEvent: type=LMouseDown loc=(890,99) time=13052.7 flags=0 win=0x0 winNum=131 ctxt=0x0 evNum=0 click=2 buttonNumber=0 pressure=1 deviceID:0x0 subtype=0
NSEvent: type=LMouseDown loc=(890,99) time=13052.7 flags=0 win=0x0 winNum=131 ctxt=0x0 evNum=0 click=2 buttonNumber=0 pressure=1 deviceID:0x0 subtype=0

要在终端/控制台上运行脚本,它必须是后台任务

$ python app.py &

你可以稍后用ps杀死它:

$ ps
  PID TTY           TIME CMD
16059 ttys001    0:00.03 /bin/bash -l
16124 ttys001    0:00.77 python test.py
$ kill -9 16124

相关问题 更多 >