我正在尝试利用 OSX 的 HID 事件。我找到了一个片段来测试它。但是,我的代码似乎总是以 EXC_BAD_ACCESS 失败CFMachPortCreateRunLoopSource
。似乎downEventTap
是空的。阅读文档告诉我这需要在主线程上运行,我很确定我在主线程上,并且将内容包装起来 dispatch_async(dispatch_get_main_queue(), ^{
仍然给我 null。我正在从应用程序调用监听didFinishLaunching
并添加
@interface AppDelegate (){
CFRunLoopSourceRef downSourceRef;
}
这就是我认为创建事件点击的方式:
CGEventRef onKeyDown(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
NSLog(@"DOWN (%lli)", CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode));
// When it matches, I return CGEventCreate(NULL) to stop the event
return event;
}
-(void)listen{
CFMachPortRef downEventTap = CGEventTapCreate(kCGHIDEventTap,kCGHeadInsertEventTap,kCGEventTapOptionDefault,CGEventMaskBit(kCGEventKeyDown),&onKeyDown,(__bridge void *)(self));
downSourceRef = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, downEventTap, 0); //<-- Crash exc_bad_access: downEventTap = 0x0,downSourceRef= 0x0
CFRelease(downEventTap);
CFRunLoopAddSource(CFRunLoopGetCurrent(), downSourceRef, kCFRunLoopDefaultMode);
CFRelease(downSourceRef);
}