Event Tap(CFMachPortRef) problem for Hot Key- callback is not invoked
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.
Could someone help me out in identifying 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, i开发者_开发技巧nterestedEvents, 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 would pass the event kCGEventMaskForAllEvents
rather than only set the hook for certain events.
Then, in your callback function, filter the events.
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
if (type == kCGEventTapDisabledByTimeout) {
NSLog(@"Event Taps Disabled! Re-enabling");
CGEventTapEnable(eventTap, true);
return event;
}
if (type == kCGEventLeftMouseDown) {
//...
}
if (type != kCGEventKeyDown) {
//...
}
if (type == kCGEventKeyDown) {
//...
}
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.
精彩评论