Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending CGEvents keystrokes to background apps

I am trying to send enter key to a background app like this:

CGEventRef a = CGEventCreateKeyboardEvent(eventSource, 36, true);
CGEventRef b = CGEventCreateKeyboardEvent(eventSource, 36, false);
CGEventPostToPSN(&psn, a);
CGEventPostToPSN(&psn, b);

It not working, i think it's because the app has to be the front most app to receive keystrokes? Am I right? If so, is there anyway I can send this event without making the app active first? If not, then what am I doing wrong? Thanks.

like image 776
Joe Avatar asked Nov 30 '25 14:11

Joe


1 Answers

Apps that are in the background don't act on key events. You have two options for making your app handle them when it's in the background: Event Taps and +[NSEvent addLocalMonitorForEventsMatchingMask:]. The NSEvent option is pretty easy:

// A block callback to handle the events
NSEvent * (^monitorHandler)(NSEvent *);
monitorHandler = ^NSEvent * (NSEvent * theEvent){
    NSLog(@"Got a keyDown: %d", [theEvent keyCode]);
    // The block can return the same event, a different 
    // event, or nil, depending on how you want it to be 
    // handled later. In this case, being in the background, 
    // there won't be any handling regardless.
    return theEvent;
};

// Creates an object that we don't own but must keep track of to
// remove later (see docs). Here, it is placed in an ivar.
monitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask 
                                                handler:monitorHandler];

but you're already monkeying around with event taps, so you may just want to go that route.

// Creates an object that must be CFRelease'd when we're done
CFMachPortRef tap = CGEventTapCreateForPSN(myOwnPSN, 
                                       kCGTailAppendEventTap,
                                       kCGEventTapOptionDefault, 
                                       kCGEventKeyDown,
                                       myEventTapCallback, 
                                       NULL);

The callback is straightforward. See Callbacks in the Event Services reference for info.

like image 157
jscs Avatar answered Dec 03 '25 05:12

jscs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!