热键的事件 Tap(CFMachPortRef) 问题 - 未调用回调
我正在开发一个桌面应用程序,通过热键支持其中一项功能。我正在使用 Event Tap 来实现此目的。
但是,有时(随机)回调不会被调用;热键不起作用,因此该功能似乎不起作用。
我如何识别这里的问题?
以下是代码片段:
-( void )startEventTapinThread //Called in a separate thread.
{
NSAutoreleasePool *pool =[ [ NSAutoreleasePool alloc] init];
CFRunLoopRef runloop =(CFRunLoopRef)CFRunLoopGetCurrent();
CGEventMask interestedEvents = CGEventMaskBit(kCGEventFlagsChanged)|CGEventMaskBit(kCGEventKeyDown);
CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, interestedEvents, myCGEventCallback, self); //self is the object pointer our method
CFRunLoopSourceRef source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource((CFRunLoopRef)runloop , source, kCFRunLoopCommonModes);
CFRunLoopRun();
[ pool release];
}
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
CGEventType eventType = CGEventGetType(event);
//execute the code related to feature
}
I am developing a desktop application that supports one of the feature through Hot Key. I am using Event Tap for this to work.
But, sometimes (randomly) the callback is not invoked; Hot Key does not work and hence the feature seems to be not working.
How can I identify the problem here?
Following is the code snippet:
-( void )startEventTapinThread //Called in a separate thread.
{
NSAutoreleasePool *pool =[ [ NSAutoreleasePool alloc] init];
CFRunLoopRef runloop =(CFRunLoopRef)CFRunLoopGetCurrent();
CGEventMask interestedEvents = CGEventMaskBit(kCGEventFlagsChanged)|CGEventMaskBit(kCGEventKeyDown);
CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, interestedEvents, myCGEventCallback, self); //self is the object pointer our method
CFRunLoopSourceRef source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource((CFRunLoopRef)runloop , source, kCFRunLoopCommonModes);
CFRunLoopRun();
[ pool release];
}
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
CGEventType eventType = CGEventGetType(event);
//execute the code related to feature
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会传递事件
kCGEventMaskForAllEvents
而不是只为某些事件设置挂钩。然后,在回调函数中过滤事件。
I would pass the event
kCGEventMaskForAllEvents
rather than only set the hook for certain events.Then, in your callback function, filter the events.
您的问题的解决方案很可能在 此问题的最佳答案中描述。如果我有代表分数,我会将这个问题标记为骗局。
The solution to your problem is most likely described in the top answer to this question. I would mark this question as a dupe if I had the rep score to do so.