将CGEvents键击发送到后台应用程序

时间:2011-05-21 02:50:58

标签: objective-c cocoa macos nsevent cgeventtap

我正在尝试将Enter键发送到这样的后台应用:

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

它不起作用,我认为这是因为应用程序必须是接收击键的最前端的应用程序?我对吗?如果是这样,无论如何我可以发送此事件而不首先激活应用程序?如果没有,那么我做错了什么? 感谢。

1 个答案:

答案 0 :(得分:3)

背景中的应用不会对关键事件起作用。您可以通过两种方式让应用在后台处理它们:Event Taps+[NSEvent addLocalMonitorForEventsMatchingMask:]NSEvent选项非常简单:

// 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];

但是你已经用事件点击进行了整理,所以你可能只想走那条路。

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

回调很简单。有关信息,请参阅“活动服务”参考中的Callbacks