I'm studying how to implement key event capturing and callback for a OSX no-GUI command-line tool within its process space, in C, using CoreFoundation only, (no Cocoa, no NSEvents). Upon some research, I could easily put together this MCVE on "global level" (which requires running the program with root privileges), but could not figure out what to do for capturing and processing key events in the program's process space only. I also haven't found documentation on how this can be done. I have found some questions from this area on SO, but all of them were Cocoa API based. I'll gladly provide any additional information needed.
// gcc -Wall -o cftest cftest.c -framework ApplicationServices
// sudo test
#include
CGEventRef testEventCallback(CGEventTapProxy proxy,
CGEventType type,
CGEventRef event,
void *refcon)
{
printf( " Event Type: %d\n", type );
return event;
}
int main(int argc, char *argv[])
{
CFMachPortRef eventPort;
CFRunLoopSourceRef eventSrc;
CFRunLoopRef runLoop;
CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp);
eventPort = CGEventTapCreate(kCGSessionEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionListenOnly,
mask,
testEventCallback,
NULL );
if ( eventPort == NULL ){
printf( "NULL eventPort\n" );
return 1;
}
eventSrc = CFMachPortCreateRunLoopSource(NULL, eventPort, 0);
if ( eventSrc == NULL ){
printf( "NULL eventSrc\n" );
return 1;
}
runLoop = CFRunLoopGetCurrent();
if ( runLoop == NULL ){
printf( "NULL runLoop\n" );
return 1;
}
CFRunLoopAddSource(runLoop, eventSrc, kCFRunLoopDefaultMode);
CFRunLoopRun();
return 0;
}