开发者

How to trap global keydown/keyup events in cocoa

开发者 https://www.devze.com 2023-03-14 03:18 出处:网络
I want to trap, modify and divert all the keydown/keyup events in the system within my cocoa app. I know abou开发者_StackOverflowt CGEventTapCreate but, didn\'t found any working code from net.

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

Thanks


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消