How to trap global keydown/keyup events in cocoa

删除回忆录丶 提交于 2019-12-24 06:35:02

问题


I want to trap, modify and divert all the keydown/keyup events in the system within my cocoa app. I know about CGEventTapCreate but, didn't found any working code from net.

Thanks


回答1:


Found Solution:

self.machPortRef =  CGEventTapCreate(kCGSessionEventTap,
                                             kCGTailAppendEventTap,
                                             kCGEventTapOptionDefault,
                                             CGEventMaskBit(kCGEventKeyDown),
                                             (CGEventTapCallBack)eventTapFunction,
                                             self);
        if (self.machPortRef == NULL)
        {
            printf("CGEventTapCreate failed!\n");
        } else {
            self.eventSrc = CFMachPortCreateRunLoopSource(NULL, self.machPortRef, 0);
            if ( self.eventSrc == NULL )
            {
                printf( "No event run loop src?\n" );
            }else {
                CFRunLoopRef runLoop =  CFRunLoopGetCurrent(); //GetCFRunLoopFromEventLoop(GetMainEventLoop ()); 

                // Get the CFRunLoop primitive for the Carbon Main Event Loop, and add the new event souce
                CFRunLoopAddSource(runLoop, self.eventSrc, kCFRunLoopDefaultMode);

            }
        }

Properties :

CFMachPortRef machPortRef;
CFRunLoopSourceRef  eventSrc;

Event Handler:

 CGEventRef eventTapFunction(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
    //printf("eventTap triggered\n");
    return event;
}


来源:https://stackoverflow.com/questions/6421718/how-to-trap-global-keydown-keyup-events-in-cocoa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!