OSX/Cocoa:监听系统范围的鼠标拖动事件

Zig*_*rth 4 macos events cocoa objective-c listener

嗨,我是cocoa编程的新手,想知道如何为系统范围的事件(例如鼠标拖动)创建一个监听器.我已将此添加到我的应用程序中(我在另一篇文章中看到了它):

static CGEventRef eventFunction(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
    printf("event triggered\n");
    return event;
}
Run Code Online (Sandbox Code Playgroud)

但它永远不会被调用,我不知道我打算在哪里注册回叫.

omz*_*omz 7

观看全局鼠标事件的最简单方法是使用NSEvent类方法addGlobalMonitorForEventsMatchingMask:handler:

例:

[NSEvent addGlobalMonitorForEventsMatchingMask:NSLeftMouseDraggedMask 
                                       handler:^(NSEvent *event) {
    NSLog(@"Dragged...");
}];
Run Code Online (Sandbox Code Playgroud)

请注意,这仅适用于其他应用程序,要在您自己的应用程序中获取这些事件,您必须添加其他本地事件处理程序.