我正在尝试使用cgcreateeventtap来监控全局鼠标点击,但是当我这样做时,它似乎阻止了与自己的应用程序的交互。鼠标在其他运行应用程序中的点击工作正常,但我自己的应用程序(即demoAppDelegate应用程序)没有完全响应。我可以拖动应用程序的主窗口,但红色/黄色/绿色窗口按钮灰色。DemoApp的菜单也无法克利克。

这对我来说似乎非常奇怪,我一直无法弄清楚。使用事件抽头的示例是很少的,因此任何建议都非常感谢。

#import "DemoAppDelegate.h"

CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
    CGPoint location = CGEventGetLocation(event);
    NSLog(@"location:  (%f, %f) - %@\n", location.x, location.y, (NSString*)refcon);
    return event;
}

@implementation DemoAppDelegate
@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    CFMachPortRef eventTap;
    CGEventMask        eventMask;
    CFRunLoopSourceRef runLoopSource;
    eventMask = 1 << kCGEventLeftMouseDown;
    eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap,
                                1, eventMask, myCGEventCallback, @"mydata");
    runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource,
                       kCFRunLoopCommonModes);
    CGEventTapEnable(eventTap, true);
    CFRunLoopRun();
}
@end
.

有帮助吗?

解决方案

When you create a Cocoa application, -[NSApplication run] is responsible for running the event loop — it runs the run loop, and dispatches events. This means that you should remove that

CFRunLoopRun();

call at the bottom of your -applicationDidFinishLaunching: method implementation, since it prevents -applicationDidFinishLaunching: from returning and also prevents NSApplication from dispatching events.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top