开发者

Sending CGEvents keystrokes to background apps

开发者 https://www.devze.com 2023-03-07 16:13 出处:网络
I am trying to 开发者_如何学JAVAsend enter key to a background app like this: CGEventRef a = CGEventCreateKeyboardEvent(eventSource, 36, true);

I am trying to 开发者_如何学JAVAsend 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.


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.

0

精彩评论

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